我有一个包含三列的熊猫数据帧,如下所示:
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
对于项目T1
和T2
不按字母顺序排列的任何行(例如"Netherlands"
和"Bulgaria"
),我希望交换项目并更改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ᴘᴇᴇᴅ”的回答那么简洁,但要努力
这里是一个有趣的和创造性的方式使用numpy工具
选项1
布尔索引。你知道吗
选项2
df.eval
选项3
df.query
相关问题 更多 >
编程相关推荐