[英]Fill values in dataframe by matching column names to dictionary
I need to map the values of a dictionary to the names of the columns of a dataframe.我需要将字典的值 map 转换为 dataframe 的列名。 If there is no value I would like to fill up the dataframe with zeros如果没有值,我想用零填充 dataframe
import pandas as pd
final_df = pd.DataFrame(columns=['Chat','Email','Phone','VM','web','Sum unique values', 'Date', 'Time', 'Month Selected', 'Year Selected'])
export_dict ={'Chat': 1, 'Email': 4, 'VM': 15}
Result:结果:
Chat Email Phone VM web Sum unique values Date Time Month Selected Year Selected
1 4 0 15 0 20 0 0 0 0
You can add new row to DataFrame by DataFrame.loc
:您可以通过DataFrame.loc
向 DataFrame 添加新行:
final_df.loc[0] = export_dict
and then replace misisng values by DataFrame.fillna
:然后用DataFrame.fillna
替换错误值:
final_df = final_df.fillna(0)
print (final_df)
Chat Email Phone VM web Sum unique values Date Time Month Selected \
0 1 4 0 15 0 0 0 0 0
Year Selected
0 0
Another solutions are with DataFrame costructor for improve performance - here is added all columns by DataFrame.reindex
:另一种解决方案是使用 DataFrame 构造函数来提高性能 - 这里是通过DataFrame.reindex
添加所有列:
export_dict ={'Chat': 1, 'Email': 4, 'VM': 15}
c =['Chat','Email','Phone','VM','web','Sum unique values',
'Date', 'Time', 'Month Selected', 'Year Selected']
final_df = pd.DataFrame([export_dict]).reindex(c, axis=1, fill_value=0)
print (final_df)
Chat Email Phone VM web Sum unique values Date Time Month Selected \
0 1 4 0 15 0 0 0 0 0
Year Selected
0 0
Or by merge
of dictionaries, order is important of passed value - need first zero dict for avoid overwrite values by 0
:或者通过merge
字典,顺序对于传递的值很重要 - 需要第一个零字典以避免用0
覆盖值:
final_df = pd.DataFrame([{**dict.fromkeys(c, 0), **export_dict}])
print (final_df)
Chat Email Phone VM web Sum unique values Date Time Month Selected \
0 1 4 0 15 0 0 0 0 0
Year Selected
0 0
If change order all values are 0
:如果更改顺序所有值都是0
:
print ( pd.DataFrame([{**export_dict,**dict.fromkeys(c, 0)}]))
Chat Email VM Phone web Sum unique values Date Time Month Selected \
0 0 0 0 0 0 0 0 0 0
Year Selected
0 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.