我如何对具有相同行数但没有匹配列名的 2 个数据帧执行连接?
How do i perform join on 2 dataframes that have same number of rows but no matching column names?
我正在尝试为数据帧的所有特征中缺失的 NaN 值绘制直方图
为此,我为缺失的 NaN 值创建了一个数据框
数据帧缺失值
0
-----
0 0
1 14
2 800
.
.
84 2344
然后我有这个主数据框,它有多个我不关心的列,因为我只想要这个数据框的行名
主数据框
0 1
---------
F1 3 3
F2 4 3
.
.
F85 5 2
我如何合并/连接这 2 个数据帧,最终输出应该是这样的(主数据帧中的列无关紧要,因为我想绘制所有特征中缺失值的数量,即 F1、F2、...F85)
F1 0
F2 14
F3 800
.
.
F85 2344
我们可以使用 pandas
的 concat
方法轻松做到这一点。
`
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)
`
您将根据您的要求获得准确的值。
假设您的数据框是 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用行号替换两个数据帧中的索引,然后合并数据帧
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
我正在尝试为数据帧的所有特征中缺失的 NaN 值绘制直方图 为此,我为缺失的 NaN 值创建了一个数据框
数据帧缺失值
0
-----
0 0
1 14
2 800
.
.
84 2344
然后我有这个主数据框,它有多个我不关心的列,因为我只想要这个数据框的行名
主数据框
0 1
---------
F1 3 3
F2 4 3
.
.
F85 5 2
我如何合并/连接这 2 个数据帧,最终输出应该是这样的(主数据帧中的列无关紧要,因为我想绘制所有特征中缺失值的数量,即 F1、F2、...F85)
F1 0
F2 14
F3 800
.
.
F85 2344
我们可以使用 pandas
的 concat
方法轻松做到这一点。
`
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)
`
您将根据您的要求获得准确的值。
假设您的数据框是 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用行号替换两个数据帧中的索引,然后合并数据帧
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