问题:python pandas dataframe列转换为dict键和值

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

数据框:

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

我需要将区域定义为键,在dict中计为值。先感谢您。

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.


回答 0

如果lakes是您DataFrame,则可以执行以下操作

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

If lakes is your DataFrame, you can do something like

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

回答 1

使用大熊猫可以做到:

如果lakes是您的DataFrame:

area_dict = lakes.to_dict('records')

With pandas it can be done as:

If lakes is your DataFrame:

area_dict = lakes.to_dict('records')

回答 2

如果您想和熊猫玩耍,也可以这样做。但是,我喜欢punchagan的方式。

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

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

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。