引言
DataFrame 是由多种类型的列构成的二维标签数据结构。
简单理解是类似于 Excel 、 SQL 表的结构。
DataFrame 是最常用的 Pandas 对象,与 Series 一样,DataFrame 支持多种类型的输入数据:
- 一维 ndarray、列表、字典、Series 字典
- 二维 numpy.ndarray
结构多维数组或记录多维数组
- Series
- DataFrame
构建 DataFrame
同 Excel 一样, DataFrame 拥有行标签( index )和列标签( columns ),可以理解为 Excel 的行和列。
在构建 DataFrame 的时候,可以有选择的传递 index 和 columns 参数。
这样可以确保生成的 DataFrame 里包含索引或列。
注意: Python > = 3.6,且 Pandas > = 0.23,数据是字典,且未指定 columns 参数时,DataFrame 的列按字典的插入顺序排序。
Python < 3.6 或 Pandas < 0.23,且未指定 columns 参数时,DataFrame 的列按字典键的字母排序。
Series 字典或字典构建 DataFrame
先看一个简单的示例:
d = {
'one': pd.Series([1., 2., 3.], index=['a', 'b', 'c']),
'two': pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(d)
print(df)
结果如下:
one two
a 1.0 1.0
b 2.0 2.0
c 3.0 3.0
d NaN 4.0
在通过 Series 构建 DataFrame 的时候,生成的 index (索引)是每个 Series 索引的并集。
先把嵌套字典转换为 Series 。如果没有指定列, DataFrame 的列就是字典键的有序列表。
这里我们在字典中使用两个字符串 one 和 two 作为字典的 key ,在构造 DataFrame 时会自动的使用我们的字典的 key 作为自己的 columns (列)。
如果我们在构造 DataFrame 手动指定索引,那么将会使用我们自行指定的索引,示例如下:
df1 = pd.DataFrame(d, index=['d', 'b', 'a'])
print(df1)
结果如下:
one two
d NaN 4.0
b 2.0 2.0
a 1.0 1.0
如果我们同时指定 index 和 column ,那么 DataFrame 也将会使用我们指定的索引和列,如果我们指定的 index 或者 column 不存在,将会使用 NaN 进行默认值填充,示例如下:
df2 = pd

最低0.47元/天 解锁文章
1572

被折叠的 条评论
为什么被折叠?



