我有一個帶有郵政編碼的熊貓資料框。我還有一本字典,其中鍵 = zipkode 和值 = 區域
詞典
my_regions = {8361: 'Central region', 8381: 'Central region', 8462: 'North region', 8520: 'South region', 8530: 'Central region', 8541: 'South region'}
資料框有一個 col 名稱
df["zipcode"]= [8462, 8361, 8381,8660,8530,8530]
我想用dict值(區域名稱)向資料幀df添加一個新col,當回圈看到資料幀中的郵政編碼==到dict.keys中的zipkode時
我試過這個
my_regions_list = []
for keyname in my_regions:
for zipcode in df.zipcode:
if zipcode == my_regions.keys():
my_regions_list.append(my_regions.values())
# df["region"] = df.append(my_regions.values())
df =df.insert(column="region", value = my_r)
該串列為空,這不會將新行添加到現有資料框中...
我也嘗試將其轉換為資料框,但沒有任何意義
df1 = pd.DataFrame(list(my_regions.items()),columns = ['ZIPCODE','REGIONNAME'])
uj5u.com熱心網友回復:
您可以使用.map():
df = pd.DataFrame({"zipcode": [8462, 8361, 8381, 8660, 8530, 8530]})
my_regions = {
8361: "Central region",
8381: "Central region",
8462: "North region",
8520: "South region",
8530: "Central region",
8541: "South region",
}
df["name"] = df["zipcode"].map(my_regions)
print(df)
印刷:
zipcode name
0 8462 North region
1 8361 Central region
2 8381 Central region
3 8660 NaN
4 8530 Central region
5 8530 Central region
uj5u.com熱心網友回復:
我將繼續這樣做,盡管.map()據說比.replace()僅僅因為結果不同而更快,并且其他人可能會發現其中一個更適合他們的用例。
請注意,主要區別在于.replace()如果未找到映射,原始值將保持不變,而為不存在的映射.map()生成。NaN
df["regions"] = df["zipcode"].replace(my_regions)
演示:
In [5]: df
Out[5]:
zipcode
0 8462
1 8361
2 8381
3 8660
4 8530
5 8530
In [6]: df["regions"] = df["zipcode"].replace(my_regions)
In [7]: df
Out[7]:
zipcode regions
0 8462 North region
1 8361 Central region
2 8381 Central region
3 8660 8660
4 8530 Central region
5 8530 Central region
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/451078.html
上一篇:字典到串列映射
