另一种常用的方式是包含字典的嵌套字典。
In [9]: import pandas as pd
In [10]: pop={'Nevada':{2001:2.4,2002:2.9},
...: 'Ohio':{2001:1.5,2001:1.7,2002:3.6}}
In [11]: frame3=pd.DataFrame(pop)
In [12]: frame3
Out[12]:
Nevada Ohio
2001 2.4 1.7
2002 2.9 3.6
可以将使用类似NumPy的语法对DataFrame进行转置操作(调换行和列):
In [13]: frame3.T
Out[13]:
2001 2002
Nevada 2.4 2.9
Ohio 1.7 3.6
内部字典的key被联合,排序后形成了结果的索引。如果已经显示指明索引的话没内部的字典的key将不会被排序。
In [14]: pd.DataFrame(pop,index=[2001,2002,2003])
Out[14]:
Nevada Ohio
2001 2.4 1.7
2002 2.9 3.6
2003 NaN NaN
5.1.3 索引对象
panda中的索引对象是用于储存轴标签和其他元数据的。在构造Series或DataFrame时,所使用的任意数组或者标签序列都可以在内部转换为索引对象。
In [1]: import pandas as pd
In [2]: obj=pd.Series(range(3),index=['a','b','c'])
In [3]: index=obj.index
In [4]: index
Out[4]: Index(['a', 'b', 'c'], dtype='object')
In [5]: index[1:]
Out[5]: Index(['b', 'c'], dtype='object')
索引对象是不可变的,因此无法被修改。
In [6]: index[1]='d'
Traceback (most recent call last):
File "<ipython-input-6-8be6e68dba2d>", line 1, in <module>
index[1]='d'
File "/opt/anaconda3/lib/python3.8/site-packages/pandas/core/indexes/base.py", line 4277, in __setitem__
raise TypeError("Index does not support mutable operations")
TypeError: Index does not support mutable operations
为啥是不可变的呢,不变性使得在多种数据结构中分享索引对象更为安全。
In [21]: obj2.index is labels
Out[21]: True
In [22]: labels=pd.Index(np.arange(3))
In [23]: labels
Out[23]: Int64Index([0, 1, 2], dtype='int64')
In [24]: obj2=pd.Series([1.5,-2.5,0],index=labels)
In [25]: obj2
Out[25]:
0 1.5
1 -2.5
2 0.0
dtype: float64
In [26]: obj2.index is labels
Out[26]: True
网友评论