python中Dataframe学习
程序员文章站
2024-01-06 13:23:34
...
pandas里面使用的numpy,其实就是在numpy的基础上,行和列都添加字典的key值。
学习连接
通过dict创建dataframe的列索引
import pandas as pd
dic2 = {'a':[1, 2, 3, 4], 'b':[5, 6, 7, 8],
'c':[9, 10, 11, 12], 'd':[13, 14, 15, 16]}
df=pd.DataFrame(columns=dic2.keys())
print(df)
实验结果:
Empty DataFrame
Columns: [a, b, c, d]
Index: []
获取数据框里面的列索引
import pandas as pd
dic2 = {'a':[1, 2, 3, 4], 'b':[5, 6, 7, 8],
'c':[9, 10, 11, 12], 'd':[13, 14,15, 16]}
df=pd.DataFrame(dic2)
x=df.keys()
print(x[0])
实验结果如下:
a
通过numpy生成0矩阵然后生成数据框
import pandas as pd
import numpy as np
data=np.zeros([2,2])
df=pd.DataFrame(data)
x=df.keys()
print(x[0])
实验结果
0
删除数据框中的行和列
import pandas as pd
import numpy as np
dic2 = {'a':[1, 2, 3, 4], 'b':[5, 6, 7, 8],
'c':[9, 10, 11, 12], 'd':[13, 14,15, 16]}
df=pd.DataFrame(dic2)
print(df)
del df['a']
print(df)
xf=df.drop([0,1],axis=0)
print(df)
print(xf)
实验结果如下:
a b c d
0 1 5 9 13
1 2 6 10 14
2 3 7 11 15
3 4 8 12 16
b c d
0 5 9 13
1 6 10 14
2 7 11 15
3 8 12 16
b c d
0 5 9 13
1 6 10 14
2 7 11 15
3 8 12 16
b c d
2 7 11 15
3 8 12 16
数据框插入行
from pandas import *
from random import *
df = DataFrame(columns=('lib', 'qty1', 'qty2'))#生成空的pandas表
for i in range(5):#插入一行<span id="transmark" style="display: none; width: 0px; height: 0px;"></span>
df.loc[i] = [randint(-1,1) for n in range(3)]
print (df)
实验结果:
lib qty1 qty2
0 0.0 -1.0 -1.0
1 0.0 -1.0 -1.0
2 1.0 0.0 -1.0
3 -1.0 -1.0 1.0
4 1.0 1.0 -1.0
数据框插入行:
from pandas import *
from random import *
df = DataFrame(columns=('lib', 'qty1', 'qty2'))#生成空的pandas表
for i in range(5):#插入一行<span id="transmark" style="display: none; width: 0px; height: 0px;"></span>
df.loc[i] = [randint(-1,1) for n in range(3)]
date=[1,2,3,4,5]
df.insert(3,'date',date)
print (df)
实验结果:
lib qty1 qty2 date
0 -1.0 0.0 0.0 1
1 1.0 0.0 1.0 2
2 1.0 0.0 1.0 3
3 0.0 1.0 0.0 4
4 -1.0 1.0 1.0 5