在网上搜过许多关于pandas.DataFrame的操作说明,都是一些基础的操作,但是这些操作组合起来还是比较费时间去正确操作DataFrame,花了我挺长时间去调整BUG的。我在这里做一些总结,方便你我他。
字典中的keys就是DataFrame里面的columns,但是没有index的值,所以需要自己设定,不设定默认是从零开始计数。
bb=pd.DataFrame(aa,index=['first','second','third']) bb Out[7]: one three two first 1 3 2 second 2 4 3 third 3 5 4 1234567从多维数组中创建就需要为DataFrame赋值columns和index,否则就是默认的,很丑的。
bb=pd.DataFrame(aa,index=[22,33,44],columns=['one','two','three']) In [15]: bb Out[15]: one two three 22 1 2 3 33 4 5 6 44 7 8 9 1234567这里的拷贝是深拷贝,改变cc中的值并不能改变bb中的值。
cc['three'][22]=5 bb Out[19]: one two three 22 1 2 3 33 4 5 6 44 7 8 9 cc Out[20]: one three 22 1 5 33 4 6 44 7 9 1234567891011121314对于一个DataFrame来说,索引是最烦的,最易出错的。
多个列名需要将输入的列名存在一个列表里,才是个collerable的变量,否则会报错。
bb[['one','three']] Out[29]: one three 22 1 3 33 4 6 44 7 9 123456这里注意冒号是必须有的,否则是索引列的了。
这种不能改变这里面的值,你只是能读值,不能写值,可能和loc()函数有关:
bb.loc[[22,33]][['one','three']]=[[2,2],[3,6]] In [32]: bb Out[32]: one two three 22 1 2 3 33 4 5 6 44 7 8 9 1234567想要改变其中的值就会报错。
In [34]: bb[['one','three']][:2]=[[2,2],[2,2]] -c:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_index,col_indexer] = value instead F:\Anaconda\lib\site-packages\pandas\core\frame.py:1999: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame return self._setitem_slice(indexer, value) 12345Iloc是按照数据的行列数来索引,不算index和columns
bb.iloc[2:3,2:3] Out[36]: three 44 9 bb.iloc[1:3,1:3] Out[37]: two three 33 5 6 44 8 9 bb.iloc[0,0] Out[38]: 1 123456789101112下面是证明:
bb.iloc[0:4,0:2]=[[9,9],[9,9],[9,9]] In [45]: bb Out[45]: one two three 22 9 9 3 33 9 9 6 44 9 9 9 1234567赋予的list基本就是按照所给index值顺序赋值,可是一般我们是要对应的index进行赋值,想要更高级的赋值就看后面的了。
这里aa是一个字典和列表的嵌套,相当于一条记录,使用keys当做index名而不是一般默认的columns名。达到了按index多列匹配的目的。由于dict()储存是混乱的,之间用dict()而不给他的index赋值会记录错乱,这一点注意值得注意。
DataFrame还有很多功能还没有涉及,等以后有涉及到,看完官网的API之后,还会继续分享,everything is ok。