pandas 如何创建一个数据框架的数据框架,其中添加了另一个数据框架中的行,但这些行在原始数据框架中没有按索引显示?

rpppsulh  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(92)

假设我有以下 Dataframe :

base_df = pd.DataFrame({'animal':['dog', 'cat'], 'noise':['bark', 'meow']}, index=[1,2])
new_info_df = pd.DataFrame({'animal':['wolf', 'sheep'], 'noise':['woof', 'baa']}, index=[1,3])

字符串
我想创建一个新的dataframe,其中包含base_df中的所有数据和new_info_df中的行,其中行的索引尚未出现在base_df中,即更新的dataframe应该等价于:

updated_df = pd.DataFrame({'animal':['dog', 'cat', 'sheep'], 'noise':['bark', 'meow', 'baa']}, index=[1,2,3])


我试过了

pd.concat([base_df, new_info_df], join='outer', axis=1)


但我最终与列‘动物‘和‘噪音‘被重复,我不想。

bttbmeg0

bttbmeg01#

你可以尝试boolean索引+ .concat

df = pd.concat([base_df, new_info_df[~new_info_df.index.isin(base_df.index)]])
print(df)

字符串
图纸:

animal noise
1    dog  bark
2    cat  meow
3  sheep   baa

des4xlb0

des4xlb02#

要创建一个包含所需列('animal'和'noise')的新数据框架,将base_df中的数据和new_info_df中的行的索引合并在一起,可以执行以下步骤:

import pandas as pd

base_df = pd.DataFrame({'animal': ['dog', 'cat'], 'noise': ['bark', 'meow']}, index=[1, 2])
new_info_df = pd.DataFrame({'animal': ['wolf', 'sheep'], 'noise': ['woof', 'baa']}, index=[1, 3])

# Get the indices that are not present in base_df
new_indices = new_info_df.index.difference(base_df.index)

# Filter new_info_df based on the new indices
filtered_new_info_df = new_info_df.loc[new_indices]

# Concatenate base_df and filtered_new_info_df
updated_df = pd.concat([base_df, filtered_new_info_df])

# Sort the index of the updated dataframe
updated_df.sort_index(inplace=True)

print(updated_df)

字符串
输出将为:

animal  noise
1    dog   bark
2    cat   meow
3  sheep    baa

相关问题