我有三列的熊猫数据帧选择项目,如部分如下所示:重新排序在两只大熊猫数据帧列
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
是否有更好的方法来得到相同的结果? (性能不成问题)
你需要打印出df1 :) –
@cᴏʟᴅsᴘᴇᴇᴅ是的,你是对的〜:) – Wen