[英]python pandas dataframe columns convert to dict key and value
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.
先感谢您。
如果lakes
是您的DataFrame
,您可以执行以下操作
area_dict = dict(zip(lakes.area, lakes.count))
With pandas it can be done as:使用熊猫可以这样做:
If lakes is your DataFrame:如果 Lakes 是您的 DataFrame:
area_dict = lakes.to_dict('records')
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}
If 'lakes' is your DataFrame, you can also do something like:如果“湖泊”是您的 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()
or @punchagan 's solution (which I prefer)或 @punchagan 的解决方案(我更喜欢)
area_dict = dict(zip(lakes.area, lakes.count))
Both should work.两者都应该工作。
Answering @Jessie Marks question, on how to use this dict(zip(***)) approach if you want to use multiple columns as keys / values, the answer is to zip the zips;回答@Jessie Marks 的问题,如果你想使用多列作为键/值,如何使用这个 dict(zip(***)) 方法,答案是压缩拉链; eg:
例如:
dict(zip(df['key'], zip(df["value col 1"], df_['value col 1'])))
or if you wish to use multiple columns as keys:或者如果您希望使用多列作为键:
dict(zip(zip(df['key 1'], df['key 2']), zip(df["value col 1"], df_['value col 1'])))
this worked for me on pandas v1.1.5 ;这在 pandas v1.1.5 上对我有用; python 3.6.13
蟒蛇 3.6.13
PS.附注。 sorry i do not respond directly under @Jessie Marks question, its new account and I cannot do that yet.
抱歉,我不会直接在@Jessie Marks 问题下回复,它的新帐户,我还不能这样做。
你需要这个
area_dict = lakes.to_dict(orient='records')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.