import pandas as pd
import numpy as np
# 一、一维数组构建
# ① Series方法
s = pd.Series(np.random.randn(2))
0 0.124839
1 1.619798
dtype: float64
df = pd.DataFrame(s)
0
0 0.124839
1 1.61979
# ② 数组
s = list("12")
df = pd.DataFrame(s)
0
0 1
1 2
# 二、二维数组
# ①、二维数组
s = np.random.randn(2,2)
df = pd.DataFrame(s)
0 1
0 1.026566 -0.306909
1 -0.185214 1.154144
# ②、两组list
s1 = list("12")
s2 = list("34")
df = pd.DataFrame([s1,s2])
0 1
0 1 2
1 3 4
# ③、Series
s1 = pd.Series(np.random.randn(2))
s2 = pd.Series(np.random.randn(2))
df = pd.DataFrame([s1,s2])
0 1
0 1.072581 0.634420
1 -0.455175 -0.087483
# ④、字典简单嵌套
data = {'a':['1','2'],'c':['5','6']}
df = pd.DataFrame(data)
a c
0 1 5
1 2 6
# ⑤、字典复杂嵌套
data = {'a':{'1':'1','2':'2'},'b':{'3':'3','4':'4'}}
df = pd.DataFrame(data) # 等价于 pd.DataFrame.from_dict(data)
df = pd.DataFrame(data).T # 等价于 pd.DataFrame.from_dict(data,orient='index')
1 2 3 4
a 1 2 NaN NaN
b NaN NaN 3 4
# 三、递增法
df = pd.DataFrame()
data = list("1234")
df = df.append(data,ignore_index=True)
0
0 1
1 2
2 3
3 4
总结:
DataFrame本质构建方法3种:
1、一维构建(list、Seires)
2、二维构建法(字典、二维、2组list)
3、累加构建法