gpt4 book ai didi

python - Pandas 将数据帧与不同的数据合并以实现特定的输出

转载 作者:太空宇宙 更新时间:2023-11-03 17:54:21 25 4
gpt4 key购买 nike

我正在尝试 pandas,并面临合并问题,f.e

打印df

                                    0                         1         2
0 plot_title title1 title2
1 x_title x x
2 y_title Speed y
3 x_val0 xv0 NaN
4 x_val1 xv1 v1
5 exp1 3159.6 3200
6 exp2 2441.2 NaN

打印 df_to 合并

            0      1
0 plot_title title
1 x_title x
2 y_title ro
3 x_val Nan
4 exp1 19
5 exp7 127

我想要实现

                                    0      1          2      3
0 plot_title title1 title2 title
1 x_title x x x
2 y_title Speed y ro
3 x_val0 xv0 NaN NaN
4 x_val1 xv1 v1 NaN
5 exp1 3159.6 3200 19
6 exp2 2441.2 NaN Nan
7 exp7 NaN NaN 127

我怎样才能做到这一点?谢谢。

更新:jeanrjc 回答后我收到一个关键错误

  File "pandas/index.pyx", line 134, in pandas.index.IndexEngine.get_loc (pandas/index.c:3812)
File "pandas/index.pyx", line 156, in pandas.index.IndexEngine.get_loc (pandas/index.c:3749)
KeyError: '0',

但是如果我用

运行它

df2 = df.merge(df_to 合并, how='outer', left_on="0", right_on=0)。我明白

这样的 df2 输出:

            0       1           0      1
0 plot_title title1 plot_title title
1 x_title x x_title x
2 y_title Speed y_title ro
3 x_val0 xv0 x_val0 NaN
4 x_val1 xv1 x_val1 NaN
5 exp1 3159.6 exp1 19
6 exp2 2441.2 exp2 NaN
7 x_val NaN x_val Nan
8 exp7 NaN exp7 127

最佳答案

您需要与“外部”模式进行合并:

df2 = df.merge(df_to merge, how='outer', left_on="0", right_on="0")

并重命名您的列:

df2.columns = range(4)

给出:

            0       1       2      3
0 plot_title title1 title2 title
1 x_title x x x
2 y_title Speed y ro
3 x_val0 xv0 NaN NaN
4 x_val1 xv1 v1 NaN
5 exp1 3159.6 3200 19
6 exp2 2441.2 NaN NaN
7 x_val NaN NaN Nan
8 exp7 NaN NaN 127

请注意,df_to_merge 中的 x_val 不在您的预期输出中,我想这是一个错误,不是吗?

编辑:

要对行重新排序:

df2 = df2.reindex(index=[1,2,3,4,7,5,6,8])
df2.index = range(1,9)

给出:

         0       1     2    3
1 x_title x x x
2 y_title Speed y ro
3 x_val0 xv0 NaN NaN
4 x_val1 xv1 v1 NaN
5 x_val NaN NaN Nan
6 exp1 3159.6 3200 19
7 exp2 2441.2 NaN NaN
8 exp7 NaN NaN 127

HTH

关于python - Pandas 将数据帧与不同的数据合并以实现特定的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28696213/

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