区别关系

2024-06-13 19:40:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我在熊猫中有一个数据框,国家之间的关系:

    country_from   country_to  points
1   Albania        Austria     10
2   Denmark        Austria     5   
3   Austria        Albania     2 
4   Greece         Norway      4   
5   Norway         Greece      5   

我试图得到关系点之间的区别,如下所示:

country_from_or_to   country_to_or_from  difference
Albania              Austria             8
Denmark              Austria             
Greece               Norway              -1

你知道怎么做吗


Tags: orto数据from关系国家countrypoints
1条回答
网友
1楼 · 发布于 2024-06-13 19:40:08

使用^{}

cols = ['country_from','country_to']
#sort values in columns
df[cols] = df[cols].apply(sorted, axis=1)
#get difference
df['difference'] = df.groupby(cols)['points'].diff(-1)
print (df)
  country_from country_to  points  difference
1      Albania    Austria      10         8.0
2      Austria    Denmark       5         NaN
3      Albania    Austria       2         NaN
4       Greece     Norway       4        -1.0
5       Greece     Norway       5         NaN

也可以将NaN替换为空空间,但在列-数值中使用字符串获取混合值,因此某些函数可以返回奇怪的输出:

cols = ['country_from','country_to']
df[cols] = df[cols].apply(sorted, axis=1)
df['difference'] = df.groupby(cols)['points'].diff(-1).fillna('')
print (df)
  country_from country_to  points difference
1      Albania    Austria      10          8
2      Austria    Denmark       5           
3      Albania    Austria       2           
4       Greece     Norway       4         -1
5       Greece     Norway       5           

相关问题 更多 >