pandas使用数组和字典创建DataFrame &DataFrame转化为字典

代码示例:

import pandas as pd
from pandas import DataFrame,Series
import numpy as np

#使用数组创建dataframe,默认行索引、默认列索引
df1 = DataFrame(np.random.randint(0,10,(3,3)))
print(df1)
'''
打印:
   0  1  2 
0  8  9  7
1  8  4  8
2  1  5  3
'''
#index执行行索引、columns指定列索引
df2 = DataFrame(np.random.randint(0,10,(3,3)),index=[1,2,3],columns=['q','w','e'])
print(df2)
'''
打印:
   q  w  e
1  1  0  7
2  8  7  5
3  7  9  5
'''

#使用字典创建dataframe(行索引由index决定,列索引由字典的键决定)
city={
    'Province': ['TianJin', 'Beijing', 'ShangHai', 'ChongQing','ShenZhen'],
    'pop': [1.3, 2.5, 1.9, 0.7,2.1],
    'year': [2019, 2019, 2019, 2019, 2019]}
df3 = DataFrame(city)
print(df3)
'''
打印:
    Province  pop  year
0    TianJin  1.3  2019
1    Beijing  2.5  2019
2   ShangHai  1.9  2019
3  ChongQing  0.7  2019
4   ShenZhen  2.1  2019
'''
#指定index
df4 = DataFrame(city,index=['TJ','BJ','SH','CQ','SZ'])
print(df4)
'''
打印:
     Province  pop  year
TJ    TianJin  1.3  2019
BJ    Beijing  2.5  2019
SH   ShangHai  1.9  2019
CQ  ChongQing  0.7  2019
SZ   ShenZhen  2.1  2019
'''

#dataframe转字典,默认参数
dict1 = df4.to_dict()
print(dict1)
'''
打印:
{
'Province': {'TJ': 'TianJin', 'BJ': 'Beijing', 'SH': 'ShangHai', 'CQ': 'ChongQing', 'SZ': 'ShenZhen'}, 
'pop': {'TJ': 1.3, 'BJ': 2.5, 'SH': 1.9, 'CQ': 0.7, 'SZ': 2.1}, 
'year': {'TJ': 2019, 'BJ': 2019, 'SH': 2019, 'CQ': 2019, 'SZ': 2019}
}
'''
#dataframe转字典,指定orient='list' 即每一列的值以列表的形式承装
dict2 = df4.to_dict(orient='list')
print(dict2)
'''
打印:
{
'Province': ['TianJin', 'Beijing', 'ShangHai', 'ChongQing', 'ShenZhen'], 
'pop': [1.3, 2.5, 1.9, 0.7, 2.1], 
'year': [2019, 2019, 2019, 2019, 2019]
}
'''

猜你喜欢

转载自blog.csdn.net/caoxinjian423/article/details/112339606