【问题标题】:concatinating two DataFrames without NaN in python在python中连接两个没有NaN的DataFrame
【发布时间】:2025-11-23 20:55:01
【问题描述】:

我有两个数据框,

df_temp,
       Age  Name    city
   0    1   Pechi   checnnai
   1    2   Sri     pune

df_po

        po
   0    er
   1    ty

我试过 pd.concat([df_temp,df_po])

 df_temp=pd.concat([df_temp,df_po],ignore_index=True)

我得到了

        Age Name    city        po
   0    1.0 Pechi   checnnai    NaN
   1    2.0 Sri     pune        NaN
   2    NaN NaN     NaN         er
   3    NaN NaN     NaN         ty

但我想要的输出是,

        Age Name    city        po
   0    1.0 Pechi   checnnai    er
   1    2.0 Sri     pune        ty

【问题讨论】:

标签: python pandas dataframe data-analysis


【解决方案1】:

axis=1 需要 axis=1 连接,因为在 concat 中默认为 axis=0 (index 连接):

df_temp=pd.concat([df_temp,df_po],axis=1)
print (df_temp)
   Age   Name      city  po
0    1  Pechi  checnnai  er
1    2    Sri      pune  ty

DataFrame.join 的替代解决方案:

df_temp=df_temp.join(df_po)
print (df_temp)
   Age   Name      city  po
0    1  Pechi  checnnai  er
1    2    Sri      pune  ty

【讨论】:

【解决方案2】:

您应该使用:ignore_index=True 肯定

我还建议在 concat 命令之前重置两个数据帧

结果 = pd.concat([df1, df2], axis=1, ignore_index=True)

祝你好运

【讨论】:

    最近更新 更多