gpt4 book ai didi

python - 合并pandas中的两个数据框

转载 作者:行者123 更新时间:2023-12-02 18:06:17 25 4
gpt4 key购买 nike

我有以下数据框

df1

<表类=“s-表”><标题>ind停留res <正文>AB10是是AB11否是

df2

<表类=“s-表”><标题>ind日期c <正文>AB1022-011AB1024-012AB1120-011AB1121-012AB1122-013

我想要以下数据框作为最终数据框

<表类=“s-表”><标题>ind日期c停留资源 <正文>AB10是是AB1022-011AB1024-012AB11没有是AB1120-011AB1121-012AB1122-013

如何使用 pandas 获得它?

最佳答案

这将满足您的问题要求:

df1 = pd.concat([
df1.reindex(columns=list(df2.columns) + list(df1.columns)[1:]),
df2.reindex(columns=list(df2.columns) + list(df1.columns)[1:])]).sort_values('ind')

输出:

    ind   date    c stay  res
0 AB10 NaN NaN yes yes
0 AB10 22-01 1.0 NaN NaN
1 AB10 24-01 2.0 NaN NaN
1 AB11 NaN NaN no yes
2 AB11 20-01 1.0 NaN NaN
3 AB11 21-01 2.0 NaN NaN
4 AB11 22-01 3.0 NaN NaN

如果您想要空字符串而不是 NaN 值,请附加 .fillna(''):

    ind   date    c stay  res
0 AB10 yes yes
0 AB10 22-01 1.0
1 AB10 24-01 2.0
1 AB11 no yes
2 AB11 20-01 1.0
3 AB11 21-01 2.0
4 AB11 22-01 3.0

一个稍微短一点的替代方案是先使用 concat() 然后对列进行排序:

df1 = pd.concat([df1, df2])[list(df2.columns) + list(df1.columns)[1:]].sort_values('ind').fillna('')

关于python - 合并pandas中的两个数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73199508/

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