1.将字典列表写入到pandas
import pandas as pd
rows = [{'buyer_percent': '23.2%', 'tier_city': '1'}, {'buyer_percent': '18.54%', 'tier_city': '2'}]
df = pd.DataFrame(rows)
print(df)
或者
import pandas as pd
rows = [{'buyer_percent': '23.2%', 'tier_city': '1'}, {'buyer_percent': '18.54%', 'tier_city': '2'}]
df = pd.DataFrame(rows,columns=['tier_city','buyer_percent'])
print(df)
需要注意的是,columns中的字段名,必须要和rows中键相同,否则df的字段为空
2.将pandas的数据转化为字典列表
import pandas as pd
rows = [{'buyer_percent': '23.2%', 'tier_city': '1'}, {'buyer_percent': '18.54%', 'tier_city': '2'}]
df = pd.DataFrame(rows,columns=['tier_city','buyer_percent'])
使用to_dict转换成字典
(1)orient = ’index' 根据索引创建字典
df.to_dict(orient = 'index')
(2)orient = 'records' 根据字段名创建字典
df.to_dict(orient = 'records')
import pandas as pd
# 设置每列宽度
pd.set_option('max_colwidth', 20)
# 显示所有列
pd.set_option('display.max_columns', None)
# 显示所有行
pd.set_option('display.max_rows', None)
# 不换行
pd.set_option('expand_frame_repr', False)