我有一個列,其中包含“都柏林 2”、“都柏林 4”等文本。我需要檢查多達 24 個都柏林。
我想做類似的事情:
if df["Postcode"] == "Dublin 2":
df["Popularity"] == 10
elif df["Postcode"] == "Dublin 3":
df["Popularity"] == 3
等等
我試過使用條件和 np.select,它有效,但對于我擁有的都柏林數量來說這是不可行的。
conditions = [
df['Dublin Postcode'].str.contains('Dublin 1'),
df['Dublin Postcode'].str.contains('Dublin 2'),
]
values = [10,3]
df['Popularity'] = np.select(conditions, values, default=5)
有沒有更聰明的方法讓它作業?在這個階段,我不能只見樹木不見森林!
uj5u.com熱心網友回復:
您可以創建一個從字串到人口的字典,例如:
d = {'Dublin 2': 10,...}
那么你可以像這樣使用應用程式:
df["Popularity"] = df["Postcode"].apply(lambda x: d[x])
uj5u.com熱心網友回復:
我認為你可以使用apply:
import pandas as pd
postcode_to_popularity = {"Dublin 2": 10, "Dublin 3": 3} # add your other mappings here
df = pd.DataFrame({"Postcode": ["Dublin 2", "Dublin 3", "Unknwown", "Dublin 2"]}) # here you use your own dataframe
df["Popularity"] = df["Postcode"].apply(lambda postcode: postcode_to_popularity.get(postcode))
print(df)
這會給你這個:
Postcode Popularity
0 Dublin 2 10.0
1 Dublin 3 3.0
2 Unknwown NaN
3 Dublin 2 10.0
我希望這回答了你的問題 !
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/397613.html
上一篇:如果為真,很難理解如何停止回圈
