简体   繁体   English

如何连接具有不同 N 行的 Pandas 数据帧?

[英]How to concatenate Pandas dataframes with different N rows?

Assume the following dataframe df1 :假设以下数据帧df1

     A
1    123
2    456
3    765
4    987
5    456
6    234
7    111
8    222
9    677
10   55

and dataframe df2 :和数据帧df2

     B
1    333344
2    665577
3    889900
4    111111

I've tried doing this with pd.append(ignore_index=True) and pd.concat(axis=1, ignore_index=True) however the result is:我试过用pd.append(ignore_index=True)pd.concat(axis=1, ignore_index=True)但结果是:

     A      B
1    123    333344
2    456    665577
3    765    889900
4    987    111111
5    456    NaN
6    234    NaN
7    111    NaN
8    222    NaN
9    677    NaN
10   55     NaN

However, my desired result would be:但是,我想要的结果是:

     A      B
1    123    NaN
2    456    NaN
3    765    NaN
4    987    NaN
5    456    NaN
6    234    NaN
7    111    333344
8    222    665577
9    677    889900
10   55     111111

Do you have any suggestions on how to accomplish this?您对如何实现这一目标有什么建议吗?

Let us do让我们做

df2.index = df1.index[-len(df2):]
df = pd.concat([df1,df2],axis=1)
df
      A         B
1   123       NaN
2   456       NaN
3   765       NaN
4   987       NaN
5   456       NaN
6   234       NaN
7   111  333344.0
8   222  665577.0
9   677  889900.0
10   55  111111.0

You may use reindex and shift您可以使用reindexshift

n = len(df1) - len(df2)
df_final = pd.concat([df1, df2.reindex(df1.index).shift(n)], axis=1)

Out[135]:
      A         B
1   123       NaN
2   456       NaN
3   765       NaN
4   987       NaN
5   456       NaN
6   234       NaN
7   111  333344.0
8   222  665577.0
9   677  889900.0
10   55  111111.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM