Python中创建DataFrame的方法
1. 从外部文件生成(如csv、xlsx、json、html等)
import pandas as pd
df = pd.read_excel('./data.xlsx')
print(df)
print(df.columns)
2. 通过字典dictionary生成
单值情况:
import pandas as pd
students = {'name':'小明',
'age':18,
'grade':'七年级'}
df_stu = pd.DataFrame(students,index=[0])
# 或者 df_stu = pd.DataFrame({'name':'小明','age':18,'grade':'七年级'},index=[0])
print(df_stu)
输出:
注意:如果不指定index会报错: ValueError: If using all scalar values, you must pass an index
多值情况:
import pandas as pd
students = {'name':['小明','小红','小马'],
'age':[13,14,15],
'grade':['七年级','八年级','九年级']}
df_stu = pd.DataFrame(students)
#df_stu = pd.DataFrame(students,index=['stu1','stu2','stu3']) 指定索引值
print(df_stu)
输出:
3. 通过list生成
import pandas as pd
list1 = [['小明',13,'七年级'],['小红',14,'八年级'],['小马',15,'九年级']]
list2 = ['name','age','grade']
df_stu = pd.DataFrame(columns=list2,data=list1)
print(df_stu)
输出:
4. 通过numpy的array生成
import pandas as pd
import numpy as np
arr = np.arange(12).reshape(3,4)
df_arr = pd.DataFrame(arr)
print(df_arr)
输出:
5. 通过pandas的Series
import pandas as pd
students = {'name':['小明','小红','小马'],
'age':[13,14,15],
'grade':['七年级','八年级','九年级']}
s1 = pd.Series(students['name'])
s2 = pd.Series(students['age'])
s3 = pd.Series(students['grade'])
df_stu = pd.DataFrame([s1,s2,s3],index=['name','age','grade'])
print(df_stu.T)
输出: