python pandas数据框列转换为dict键和值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18012505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:43:10  来源:igfitidea点击:

python pandas dataframe columns convert to dict key and value

pythonpandasdataframedictionarydata-conversion

提问by perigee

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?

我有一个包含多列的 Pandas 数据框,我想从两列构建一个 dict:一个作为 dict 的键,另一个作为 dict 的值。我怎样才能做到这一点?

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.

我需要将区域定义为键,在字典中算作值。先感谢您。

采纳答案by punchagan

If lakesis your DataFrame, you can do something like

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

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

回答by user2643517

With pandas it can be done as:

使用熊猫可以这样做:

If lakes is your DataFrame:

如果 Lakes 是您的 DataFrame:

area_dict = lakes.to_dict('records')

回答by SammyRod

You can also do this if you want to play around with pandas. However, I like punchagan's way.

如果你想玩大熊猫,你也可以这样做。然而,我喜欢punagan的方式。

# 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}