我是熊貓圖書館的新手。
我正在研究一個如下所示的資料集:

假設我想減去表中的分數。
如果 **point score** 列中的分數低于 1000 ,我想減去 100 ,如果分數高于 1000 ,我想
減去 200 。我該怎么做呢。
代碼 :
import pandas as pd
df = pd.read_csv("files/Soccer_Football Clubs Ranking.csv")
df.head(4)
uj5u.com熱心網友回復:
采用:
np.where(df['point score']<1000, df['point score']-100, df['point score']-200)
示范:
test = pd.DataFrame({'point score':[14001,200,1500,750]})
np.where(test['point score']<1000, test['point score']-100, test['point score']-200)
輸出:

根據評論:
temp = test[test['point score']<1000]
temp=temp['point score']-100
temp2 = test[test['point score']>=1000]
temp2=temp2['point score']-200
temp.append(temp2)
另一種解決方案:
out = []
for cell in test['point score']:
if cell < 1000:
out.append(cell-100)
else:
out.append(cell-200)
test['res'] = out
第四種解決方案:
test['point score']-(test['point score']<1000).replace(False,200).replace(True,100)
uj5u.com熱心網友回復:
您可以在不顯式使用 numpy 的情況下實作矢量代碼(盡管 pandas 無論如何都使用 numpy),并保留矢量代碼:
# example 1
df['map'] = df['point score'] - df['point score'].gt(1000).map({True: 200, False: 100})
# example 2, multiple criteria
# -100 below 1000, -200 below 2000, -300 above 3000
df['cut'] = df['point score'] - pd.cut(df['point score'], bins=[0,1000,2000,float('inf')], labels=[100, 200, 300]).astype(int)
輸出:
point score map cut
0 800 700 700
1 900 800 800
2 1000 900 900
3 2000 1800 1800
4 3000 2800 2700
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/469023.html
標籤:python-3.x 熊猫
上一篇:React無法決議字串物件
