gpt4 book ai didi

python - 重新排序两个 pandas DataFrame 列中的选择项

转载 作者:行者123 更新时间:2023-11-28 19:42:29 24 4
gpt4 key购买 nike

我有一个包含三列的 pandas DataFrame,如下所示:

data = {'T1': {0: 'Belarus', 1: 'Netherlands', 2: 'France', 3: 'Faroe Islands', 
4: 'Hungary'}, 'T2': {0: 'Sweden', 1: 'Bulgaria', 2: 'Luxembourg',
3: 'Andorra', 4: 'Portugal'}, 'score': {0: -4, 1: 2, 2: 0, 3: 1, 4: -1}}
df = pd.DataFrame(data)
# T1 t2 score
#0 Belarus Sweden -4
#1 Netherlands Bulgaria 2
#2 France Luxembourg 0
#3 Faroe Islands Andorra 1
#4 Hungary Portugal -1

对于项目 T1T2 不按字母顺序排列的任何行(例如,“荷兰”“保加利亚” "), 我想交换项目并更改 score 的符号。

我想出了一个怪物:

df.apply(lambda x: 
pd.Series([x["T2"], x["T1"], -x["score"]])
if (x["T1"] > x["T2"])
else pd.Series([x["T1"], x["T2"], x["score"]]),
axis=1)
# 0 1 2
#0 Belarus Sweden -4
#1 Bulgaria Netherlands -2
#2 France Luxembourg 0
#3 Andorra Faroe Islands -1
#4 Hungary Portugal -1

是否有更好的方法来获得相同的结果? (性能不是问题。)

最佳答案

不像@cᴏʟᴅsᴘᴇᴇᴅ的回答那么整洁,但工作

df1=df[['T1','T2']]
df1.values.sort(1)
df1['new']=np.where((df1!=df[['T1','T2']]).any(1),-df.score,df.score)

df1
Out[102]:
T1 T2 new
0 Belarus Sweden -4
1 Bulgaria Netherlands -2
2 France Luxembourg 0
3 Andorra Faroe Islands -1
4 Hungary Portugal -1

关于python - 重新排序两个 pandas DataFrame 列中的选择项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46231086/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com