创建DataFrame对象
语法:
pandas.DataFrame( data, index, columns, dtype, copy)
data 支持多种数据类型,如:ndarray,series,map,lists,dict,constant和另一个DataFrame。
index 行标签,如果没有传递索引值,默认值为0,1,2,3,4.......
columns 列标签,如果没有传递索引值,默认值为0,1,2,3,4.......
dtype 每列的数据类型
copy 是否复制数据,默认值为False
创建空DataFrame对象
import pandas as pd
df = pd.DataFrame()
print (df)
利用列表创建
#利用单层list
import pandas as pd
x = [1,2,3,4,5,6]
df = pd.DataFrame(x,dtype=np.float32)
print(df)
#利用双层list
import pandas as pd
x = [
["tom",10],
["jack",20],
["mike",30]
]
#df = pd.DataFrame(x,columns=['name','age'])
#如果是True,那么x数据不改变
df = pd.DataFrame(x,columns=['name','age','sex'],copy=True)
df['age'] = 100
print(df)
print(x)
# 利用数据是字典的列表创建
import pandas as pd
x = [
{'a':1,'b':2},
{'a':10,'b':20,'c':30}
]
#index 行索引 columns列索引
df1 = pd.DataFrame(x)
print(df1)
df1 = pd.DataFrame(x,index=["first","second"])
print(df1)
#如果没有c,就会默认是nun
df1 = pd.DataFrame(x,index=["first","second"],columns=['a','c'])
print(df1)
利用字典创建
import pandas as pd
#利用字典创建DataFrame
#a、b是列索引,一定要设置行索引(index),否则报错
x = {'a':1,'b':2}
d1 = pd.DataFrame(x,index=['row1'])
print(d1)
'''
a b
row1 1 2'''
# 字典里面的v是列表类型创建DataFrame
#那么默认列索引是name和age
x = {
'name':['zs','ls','ww','zl'],
'age':[14,15,16,17]
}
d1 = pd.DataFrame(x)
print(d1)
'''
name age
0 zs 14
1 ls 15
2 ww 16
3 zl 17'''
print(d1['age'])
'''
0 14
1 15
2 16
3 17
Name: age, dtype: int64'''
利用Series和字典的结合来创建DataFrame
import pandas as pd
s1=pd.Series(["馒头","包子","豆浆","老碗面"])
s2=pd.Series([1,1.5,2,10])
a={
"食品":s1,
"价格":s2
}
df1=pd.DataFrame(a)
print(df1)
'''
食品 价格
0 馒头 1.0
1 包子 1.5
2 豆浆 2.0
3 老碗面 10.0 '''
列的读取
、语法
df[columns_lable]查询单列
df[columns_lable]查询多列
查询一列会进行降维DataFrame-------->Series
查询多列不变
import pandas as pd
s1=pd.Series(["馒头","包子&#