如何在python中使用panda将两列合并为一列,并且没有重复值



如何在pandas for python中执行从数据帧A到数据帧B的以下数据帧操作?我试过pivot和groupby,但我总是出错。我们非常感谢您的支持。

数据帧A

Col A Col B
100 1
100 2
200 3
200 4

使用groupby:的一个选项

out = (df
.groupby('Col A', group_keys=False, sort=False)
.apply(lambda d: d.iloc[:, ::-1].unstack().drop_duplicates())
.reset_index(drop=True).to_frame(name='Col A&B')
)

另一个带有concat:

out = (pd
.concat([df['Col B'], df['Col A'].drop_duplicates(keep='last')])
.sort_index().reset_index(drop=True).to_frame(name='Col A&B')
)

输出:

Col A&B
0        1
1        2
2      100
3        3
4        4
5      200

如果订单无关紧要,您可以stack:

out = df.stack().drop_duplicates().reset_index(drop=True).to_frame(name='Col A&B')

输出:

Col A&B
0      100
1        1
2        2
3      200
4        3
5        4

另一种可能的解决方案:

out = pd.DataFrame({'Col A&B': np.unique(df)})
out

输出:

Col A&B
0        1
1        2
2        3
3        4
4      100
5      200

最新更新