python - Pandas remove reversed duplicates across two columns
问题描述
An example DataFrame:
df = pd.DataFrame({'node_a': ['X', 'X', 'X', 'Y', 'Y', 'Y', 'Z', 'Z', 'Z'],
'node_b': ['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z'],
'value': [ 2, 8, 1, 8, 7, 3, 1, 3, 2]})
node_a node_b value
0 X X 2
1 X Y 8
2 X Z 1
3 Y X 8
4 Y Y 7
5 Y Z 3
6 Z X 1
7 Z Y 3
8 Z Z 2
I need to remove reversed duplicates, e.g. keep node_a = 'X', node_b = 'Y' but remove node_a = 'Y', node_b = 'X'.
Desired output:
node_a node_b value
0 X X 2
1 X Y 8
2 X Z 1
4 Y Y 7
5 Y Z 3
8 Z Z 2
Please note I need a general solution not specific to this actual data.
解决方案
Let's use np.sort
along axis=1
to sort node_a
and node_b
and assign these sorted columns to the dataframe then use drop_duplicates
on the dataframe to drop the duplicate entries in dataframe based on these assigned columns:
df[['x', 'y']] = np.sort(df[['node_a', 'node_b']], axis=1)
out = df.drop_duplicates(['x', 'y']).drop(['x', 'y'], 1)
Result:
print(out)
node_a node_b value
0 X X 2
1 X Y 8
2 X Z 1
4 Y Y 7
5 Y Z 3
8 Z Z 2
推荐阅读
- material-ui - 在 createMuiTheme 中添加自己的对象
- python-3.x - Python tkinter,如何一一显示消息
- sql - SQL如何保持满足某个条件的多个条目
- python - 使用 Python 的交互式 Choropleth 地图
- c# - 使 HomeController 从具有属性 session 的 BaseController 继承
- random - 在矢量巨大且大多数权重为零的情况下有效使用 Octave 的 randsample(带权重)
- reactjs - 将自定义 ca-bundle 添加到 next.js 以进行服务器端调用
- python - python日志记录设置调试级别
- asp.net - 下拉列表隐藏和显示面板
- sql - typeorm:如何正确使用 IsNotNull/IsNull?