我如何在2个具有相同行数但没有匹配列名的数据帧上执行联接?

问题描述 投票:0回答:3

我正在尝试为数据框的所有特征中的缺失NaN值绘制直方图为此,我创建了一个缺少NaN值的数据框

缺少值数据框

   0
-----
0  0
1  14
2  800
.
.
84 2344

然后,我有一个具有多个列的主数据框架,我不关心,因为我只希望该数据框架中的行名

主数据框

     0  1
---------
F1   3  3
F2   4  3
.
.
F85  5  2

我如何合并/连接这两个数据帧,最终输出应该像这样(主数据帧中的列无关紧要,因为我想在所有要素(即F1,F2,... F85)上绘制缺失值的数量]

    F1   0  
    F2   14 
    F3   800
    .
    .
    F85  2344
python pandas dataframe data-science concat
3个回答
1
投票

IIUC,您想要水平合并2个数据帧,而不管具有相同行数,不同列和索引的索引如何。从其中一些中仅选择一些列。

import pandas as pd

df1=pd.DataFrame(index=[1,2,3], data={"a": [3,6,4]})

df2=pd.DataFrame(index=["a1","v2","x"], data={"x": [-3,136,-5], "y": ["x", "y", "c"]})

df3=pd.concat([df1.reset_index(drop=True), df2["x"].to_frame().reset_index(drop=True)], axis=1, ignore_index=False)

输入:

#df1
   a
1  3
2  6
3  4
#df2
      x  y
a1   -3  x
v2  136  y
x    -5  c

输出:

#df3
   a    x
0  3   -3
1  6  136
2  4   -5

0
投票

我们可以使用concatpandas方法轻松地做到这一点。

`

df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
                    'B': ['B0', 'B1', 'B2', 'B3'],
                    'C': ['C0', 'C1', 'C2', 'C3'],
                    'D': ['D0', 'D1', 'D2', 'D3']},
                   index=[0, 1, 2, 3])

df4 = pd.DataFrame({'B': ['B2', 'B3', 'B6', 'B7'],
                    'D': ['D2', 'D3', 'D6', 'D7'],
                    'F': ['F2', 'F3', 'F6', 'F7']},
                   index=[0, 1, 2, 3])

result = pd.concat([df1, df4], axis=1, sort=False)

`

您将根据您的要求获得确切的值。


0
投票

假设您的数据帧是df1(丢失值数据帧)和df2(主数据帧)。然后您可以尝试以下方法:

df1.columns=['X']
res = df2.reset_index().join(df1.reset_index(), rsuffix='_r')[['index', 'X']].set_index('index')
print(res)

结果将是:

index      
F1        0
F2       14
F3      800
...
F85    2344

想法是使用reset_index将两个数据框中的索引替换为行号,然后合并数据框

© www.soinside.com 2019 - 2024. All rights reserved.