常见数据创建

除了学会如何从静态文件中读取数据,有时我们需要直接将接口返回的数据转换为 pandas dataframe 或生成一小段数据用于测试,这时就需要知道如何创建数据。

下面是通过常见的几种数据结构创建数据,你可以点击右侧目录进入对应内容。

在线刷题

检查 or 强化 Pandas 数据分析操作?👉在线体验「Pandas进阶修炼300题」

Note

本页面代码可以在线编辑、执行

从列表创建 DataFrame

常规方法

将下面的 list 转换为 dataframe,并指定列名为"早起Python"

l = [1,2,3,4,5]
pd.DataFrame(l,columns=['早起Python'])
早起Python
0 1
1 2
2 3
3 4
4 5

嵌套列表转换

将下面的 list 转换为 dataframe,并指定行索引为"公众号","早起Python"

l = [[1,2,3],[4,5,6]]
pd.DataFrame(l,index=['公众号','早起Python'])
0 1 2
公众号 1 2 3
早起Python 4 5 6

从字典创建 DataFrame

常规方法

执行下方代码,并将字典转换为dataframe

d = {
    "one": pd.Series([1.0, 2.0, 3.0], index=["a", "b", "c"]),
    "two": pd.Series([1.0, 2.0, 3.0, 4.0], index=["a", "b", "c", "d"]) }
pd.DataFrame(d)
one two
a 1.0 1.0
b 2.0 2.0
c 3.0 3.0
d NaN 4.0

指定索引

还是上一题的字典d,将其转换为dataframe并指定索引顺序为 d、b、a

pd.DataFrame(d, index=["d", "b", "a"])
one two
d NaN 4.0
b 2.0 2.0
a 1.0 1.0

指定列名

还是上一题的字典d,将其转换为dataframe并指定索引顺序为 d、b、a,列名为"two", "three"

pd.DataFrame(d, index=["d", "b", "a"], columns=["two", "three"])
two three
d 4.0 NaN
b 2.0 NaN
a 1.0 NaN

字典列表

将下方列表型字典转换为dataframe

d = [{"a": 1, "b": 2}, {"a": 5, "b": 10, "c": 20}]
pd.DataFrame(d)
a b c
0 1 2 NaN
1 5 10 20.0

思考

如何指定行/列索引?

从集合创建 DataFrame

常规方法

将下面的元组转换为 dataframe 且行列索引均为 1,2,3,4

t =((1,0,0,0,),(2,3,0,0,),(4,5,6,0,),(7,8,9,10,))
pd.DataFrame(t, columns=[1,2,3,4], index=[1,2,3,4])
1 2 3 4
1 1 0 0 0
2 2 3 0 0
3 4 5 6 0
4 7 8 9 10