当列不相同时,如何向dataframe中添加行?

2024-04-24 20:43:37 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,我有四列的原始数据框,称为“old_data”:

name type age location

然后我需要在这个数据框中添加一些新行,但它只有两列:

name age

要添加的新数据是一个DICT列表,称为“新数据”:

[{name:age}, {name:age}, {name:age}]

列不匹配时如何执行此操作


1条回答
网友
1楼 · 发布于 2024-04-24 20:43:37
import pandas as pd

# original data-frame
df = pd.DataFrame([{"name":"john", "type":"", "age":"12", "location":"so"},
                   {"name":"jane", "type":"", "age":"12", "location":"so"}])

# convert existing dict to array of dict's
data = {"james":"20", "rich":"30"}
new_df = pd.DataFrame([{"name":k, "age":v} for k, v in data.items()])

# use data-frame append to add to existing df, missing values will be filled with NaN
df = df.append(new_df, ignore_index=True)

print(df)

输出

  age location   name type
0  12       so   john     
1  12       so   jane     
2  20      NaN  james  NaN
3  30      NaN   rich  NaN

相关问题 更多 >