gpt4 book ai didi

python - 合并同一索引上的数据帧

转载 作者:行者123 更新时间:2023-12-01 02:42:28 25 4
gpt4 key购买 nike

我在这里找不到这个问题的答案。我有两个数据框:

index,  name,   color, day
0 Nan Nan Nan
1 b red thu
2 Nan Nan Nan
3 d green mon

index, name, color, week
0 c blue 1
1 Nan Nan Nan
2 t yellow 4
3 Nan Nan Nan

我希望结果是一个数据帧:

index,  name,   color,  day,   week  
0 c Blue Nan 1
1 b red thu Nan
2 t yellow Nan 4
3 d green mon Nan

有没有办法在添加新列的同时合并索引上的数据帧?

最佳答案

您可以使用DataFrame.combine_first :

df = df1.combine_first(df2)
print (df)
color day name week
0 blue NaN c 1.0
1 red thu b NaN
2 yellow NaN t 4.0
3 green mon d NaN

对于自定义列顺序,按 numpy.concatenate 创建列名称, pd.unique然后添加reindex_axis :

cols = pd.unique(np.concatenate([df1.columns, df2.columns]))
df = df1.combine_first(df2).reindex_axis(cols, axis=1)
print (df)
name color day week
0 c blue NaN 1.0
1 b red thu NaN
2 t yellow NaN 4.0
3 d green mon NaN

编辑:

使用重命名列:

df = df1.combine_first(df2.rename(columns={'week':'day'}))
print (df)
name color day
0 c blue 1
1 b red thu
2 t yellow 4
3 d green mon

关于python - 合并同一索引上的数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45533227/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com