![](/img/trans.png)
[英]Combine Row Index and Row Value (String) For Specific Rows in Pandas DataFrame
[英]How to combine rows in dataframe based on if a row contains a value in another row
我有一个看起来像这样的数据框,带有附加列:
ID Paired_ID ...
123_1 123_2
123_2 123_1
456_1 456_2
456_2 456_1
789_1 789_2
789_2 789_1
789_3 789_4
789_4 789_3
我想要做的是,对于特定的 ID,取其 Paired_ID 为 ID 的行,并将两行合并为一行。 我一直在尝试使用熊猫合并(
pd.merge(df, df, left_on="ID", right_on="Paired_ID"
但我得到了重复,无法弄清楚如何摆脱它们。
我想:
ID_x Paired_ID_x ID_y Paired_ID_y ...
123_1 123_2 123_2 123_1
456_1 456_2 456_2 456_1
789_1 789_2 789_2 789_1
789_3 789_4 789_4 789_3
假设是 ID 中的每个值都在 paired_ID 中。
比较'_'分隔符后的结尾并创建两个新的数据帧,
连接列轴上的数据框以获取输出。
#this extracts the ends of each value in ID and Paired_ID
A = df.ID.str.split('_').str[-1].astype(int)
B = df.Paired_ID.str.split('_').str[-1].astype(int)
#compare, filter df based on the comparison outcome and add suffixes
filter_1 = df.loc[A.le(B)].reset_index(drop=True).add_suffix('_x')
filter_2 = df.loc[~A.le(B)].reset_index(drop=True).add_suffix('_y')
#concatenate along the columns axis to get outcome
pd.concat([filter_1,filter_2],axis=1)
ID_x Paired_ID_x ID_y Paired_ID_y
0 123_1 123_2 123_2 123_1
1 456_1 456_2 456_2 456_1
2 789_1 789_2 789_2 789_1
3 789_3 789_4 789_4 789_3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.