pandas.DataFrame( data, index, columns, dtype, copy)参数含义:
参数 | 描述 |
|---|---|
data | 数据,接受的形式有:ndarray,Series, map,lists,dict,constant,DataFrame |
index | 行标签,默认为np.arange(n) |
columns | 列标签,默认为np.arange(n) |
dtype | 每列的数据类型 |
copy | 用于复制数据,默认值为False |
以下代码基于Anaconda的Jupyter编辑器,Python3.7。
print(pd.DataFrame())结果:
Empty DataFrame
Columns: []
Index: []print(pd.DataFrame([1,2,3,4,5]))结果:
0
0 1
1 2
2 3
3 4
4 5多维数组也可以
print(pd.DataFrame([["A", 10],["B",11],["C",12]], columns=["key", "value"]))结果:
key value
0 A 10
1 B 11
2 C 12使用dtype
print(pd.DataFrame([["A", 10],["B",11],["C",12]], columns=["key", "value"], dtype=float))结果
key value
0 A 10.0
1 B 11.0
2 C 12.0range(n)
默认 data = {"key":["A", "B", "C"], "value":[1,2,3]}
print(pd.DataFrame(data))结果:
key value
0 A 1
1 B 2
2 C 3加上索引
data = {"key":["A", "B", "C"], "value":[1,2,3]}
print(pd.DataFrame(data, index=["index1", "index2", "index3"])) 结果
key value
index1 A 1
index2 B 2
index3 C 3字典组成的列表可以创建DataFrame,字典键默认为列名。
print(pd.DataFrame(data, index=['index1', 'index2']))
print(pd.DataFrame(data, index=['index1', 'index2'], columns=['a', 'b']))
print(pd.DataFrame(data, index=['index1', 'index2'], columns=['a', 'c']))
print(pd.DataFrame(data, index=['index1', 'index2'], columns=['a', 'd']))结果
a b c
index1 1 2 NaN
index2 5 6 7.0
a b
index1 1 2
index2 5 6
a c
index1 1 NaN
index2 5 7.0
a d
index1 1 NaN
index2 5 NaNSeries组成的字典可以作为参数来创建DataFrame。其索引是所有Series的索引的并集。 例子:
d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
print(pd.DataFrame(d))结果:
one two
a 1.0 1
b 2.0 2
c 3.0 3
d NaN 4以2.5中创建的DataFrame为例: 读取一列
df = pd.DataFrame(d)
print(df["one"])结果:
a 1.0
b 2.0
c 3.0
d NaN
Name: one, dtype: float64添加一列
df["three"] = pd.Series([10,20,30], index=['a', 'b','c'])
print(df)结果:
one two three
a 1.0 1 10.0
b 2.0 2 20.0
c 3.0 3 30.0
d NaN 4 NaN删除一列
del df["three"]
print(df)结果:
one two
a 1.0 1
b 2.0 2
c 3.0 3
d NaN 4标签选择 可以将行标签传递给loc来选择行:
print(df.loc["b"])结果
one 2.0
two 2.0
Name: b, dtype: float64按整数位置选择 将证书位置传递给iloc()函数选择行:
print(df.iloc[2])结果:
one 3.0
two 3.0
Name: c, dtype: float64删除行 drop()函数可以来删除行(或者列): 以下函数等价:
df.drop(['b', 'c'], axis=1)
df.drop(columns=['b', 'c'])以下函数等价:
df.drop([0, 1])
df.drop(index=[0, 1])** 切片**
:运算符可以选择多行:
print(df[2:4])输出:
one two
c 3.0 3
d NaN 4新建行
使用append()函数可以新建行。附加到结尾:
df2 = pd.DataFrame([[5, 6], [7, 8]], index=['a','b'], columns = ['one','two'])
print(df.append(df2))