我有三列的熊貓數據幀選擇項目,如部分如下所示:重新排序在兩隻大熊貓數據幀列
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