![](/img/trans.png)
[英]How can I create a dictionary with 2 keys where the the first key is the index, the second key is from a list and the values from columns of a df?
[英]In Python, how can I transform a dictionary into a df column, where the keys match the df.index values?
我有一個數據幀和一個字典,dict的鍵與數據幀的索引值相同,如下所示:
A = pd.DataFrame([[1, 5, 2], [2, 4, 4], [3, 3, 1], [4, 2, 2], [5, 1, 4]],
columns=['A', 'B', 'C'], index=["1a", "2a", "3a", "4a", "5a"])
B = {'1a': 0.5, '2a': 0.75, '3a': 0.625, '4a': 0.55, '5a': 1}
如何將字典的值轉換為數據框中列的值,與其各自的鍵 - 索引值相匹配。 所以輸出將是這樣的:
A B C D
1a 1 5 2 0.5
2a 2 4 4 0.75
3a 3 3 1 0.625
4a 4 2 2 0.55
5a 5 1 4 1
新列'D'具有字典'B'中的所有值,並且數據幀中的每個索引值與dict中的對應鍵值匹配。
謝謝
您可以使用pandas.Series
包裝dict
,然后只需將其創建為列:
In [633]: A['D'] = pd.Series(B)
In [634]: A
Out[634]:
A B C D
1a 1 5 2 0.500
2a 2 4 4 0.750
3a 3 3 1 0.625
4a 4 2 2 0.550
5a 5 1 4 1.000
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.