[英]Adding keys from dict to columns headers in an existing Pandas dataframe
I have a dataframe ('DF1') and I have a dict ('dictdf'). 我有一个数据框('DF1'),我有一个字典('dictdf')。 I want to add columns headers based on the dict, those columns needs to be empty.
我想基于字典添加列标题,这些列需要为空。
DF1: DF1:
ID age
12 33
23 55
67 12
result: 结果:
ID age height eye_color ....
12 33 NA NA ....
23 55 NA NA ....
67 12 NA NA ....
This is what I tried: 这是我尝试的:
colNames = DF1.columns
for key in dictdf.keys():
colNames.append(key)
newDF = pd.DataFrame(DF1,columns=colNames)
Error: 错误:
TypeError: all inputs must be Index
Any idea on a simple solution? 有一个简单的解决方案的主意吗? I don't want to start transforming from dict to DF or the other way around.
我不想开始从dict转换为DF或其他方式。
You can use pd.DataFrame.join
with an empty dataframe with defined columns. 您可以将
pd.DataFrame.join
与具有定义的列的空数据pd.DataFrame.join
一起使用。 As a single operation, this will be more efficient than manual appending columns in a loop. 作为一个单独的操作,这将比在循环中手动添加列更为有效。
d = {'height': 120, 'eye_color': 'brown'}
df = df.join(pd.DataFrame(columns=d))
print(df)
ID age height eye_color
0 12 33 NaN NaN
1 23 55 NaN NaN
2 67 12 NaN NaN
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.