138

I have a pandas data frame with multiple columns and I would like to construct a dict from two columns: one as the dict's keys and the other as the dict's values. How can I do that?

Dataframe:

           area  count
co tp
DE Lake      10      7
Forest       20      5
FR Lake      30      2
Forest       40      3

I need to define area as key, count as value in dict. Thank you in advance.

4

6 回答 6

323

如果lakes是你的DataFrame,你可以做类似的事情

area_dict = dict(zip(lakes.area, lakes.count))
于 2013-08-02T09:42:17.350 回答
10

With pandas it can be done as:

If lakes is your DataFrame:

area_dict = lakes.to_dict('records')
于 2018-04-17T07:55:14.987 回答
3

如果你想和熊猫一起玩,你也可以这样做。但是,我喜欢潘根根的方式。

# replicating your dataframe
lake = pd.DataFrame({'co tp': ['DE Lake', 'Forest', 'FR Lake', 'Forest'], 
                 'area': [10, 20, 30, 40], 
                 'count': [7, 5, 2, 3]})
lake.set_index('co tp', inplace=True)

# to get key value using pandas
area_dict = lake.set_index('area').T.to_dict('records')[0]
print(area_dict)

output: {10: 7, 20: 5, 30: 2, 40: 3}
于 2018-11-13T23:46:40.023 回答
3

如果 'lakes' 是您的 DataFrame,您还可以执行以下操作:

# Your dataframe
lakes = pd.DataFrame({'co tp': ['DE Lake', 'Forest', 'FR Lake', 'Forest'], 
                 'area': [10, 20, 30, 40], 
                 'count': [7, 5, 2, 3]})
lakes.set_index('co tp', inplace=True)

我的解决方案:

area_dict = lakes.set_index("area")["count"].to_dict()

或@punchagan 的解决方案(我更喜欢)

area_dict = dict(zip(lakes.area, lakes.count))

两者都应该工作。

于 2021-05-03T02:00:47.673 回答
1

你需要这个

area_dict = lakes.to_dict(orient='records')
于 2022-01-14T01:27:11.713 回答
1

回答@Jessie Marks 的问题,关于如何使用这个 dict(zip(***)) 方法,如果你想使用多列作为键/值,答案是压缩拉链;例如:

dict(zip(df['key'], zip(df["value col 1"], df_['value col 1'])))

或者如果您希望使用多列作为键:

dict(zip(zip(df['key 1'], df['key 2']), zip(df["value col 1"], df_['value col 1'])))

这在 pandas v1.1.5 上对我有用;蟒蛇 3.6.13

PS。抱歉,我没有在@Jessie Marks 问题下直接回复,它的新帐户,我还不能这样做。

于 2021-05-12T01:25:39.917 回答