![](/img/trans.png)
[英]Creating a new column from existing column in the data frame based on the criteria
[英]Creating a new column in a data frame by mapping the values from a dictionary to an existing column
我有一本這樣的字典:
dictionary = {100:[1, 2], 110:[3, 4],
120:[5, 6, 7], 130:[8, 9],
140:[10, 11, 12, 13],
150:[14, 15]}
我已經有一個現有的列“ A”,並且想要創建一個新列“ B”並將值映射回每個鍵,但是以數據幀格式顯示。 這是我希望收到的輸出:
#Column A is the existing column. Column B is the new one to be created
A B
4 110
8 130
15 150
7 120
7 120
4 110
9 130
1 100
2 100
如何才能做到這一點? 幫助將不勝感激。 提前致謝!
通過理解來反轉字典。 然后將pd.Series.map
與新字典一起使用:
d = {100:[1, 2], 110:[3, 4], 120:[5, 6, 7], 130:[8, 9],
140:[10, 11, 12, 13], 150:[14, 15]}
d_rev = {w: k for k, v in d.items() for w in v}
df['B'] = df['A'].map(d_rev)
print(df)
A B
0 4 110
1 8 130
2 15 150
3 7 120
4 7 120
5 4 110
6 9 130
7 1 100
8 2 100
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.