简体   繁体   English

从 pandas dataframe 创建字典,其值为元组

[英]Create dict from a pandas dataframe with values as tuple

I have a dataframe like this:我有一个像这样的 dataframe:

>>> df = pd.DataFrame(np.array([[1, 2], ['a', 'b']]), columns=['col1', 'col2'])
>>> df
  col1 col2
0    1    2
1    a    b

What I am trying to do is to create a dict from this dataframe where row index is the key and col1 and col2 are a value in a tuple form for my dict.我要做的是从这个 dataframe 创建一个字典,其中行索引是键,col1 和 col2 是我的字典的元组形式的值。 Here is what I am doing but this returns a list:这是我正在做的,但这会返回一个列表:

>>> import numpy as np
>>> import pandas as pd
>>> df.T.to_dict('list')
{0: ['1', '2'], 1: ['a', 'b']}

Here is what I am trying to get:这是我想要得到的:

{0: ('1', '2'), 1: ('a', 'b')}

Lets try我们试试看

df.agg(tuple,1).to_dict()

Another way is to take the dict you have apply a dict comprehension:另一种方法是采用你有应用字典理解的字典:

>>> {k: tuple(v) for k, v in df.T.to_dict("list").items()}
{0: ('1', '2'), 1: ('a', 'b')}

Not sure about the speed but with itertuples不确定速度,但使用itertuples

dict(zip(df.index, df.itertuples(index=False, name=None)))
{0: ('1', '2'), 1: ('a', 'b')}

Or或者

dict(zip(df.index,map(tuple,df.values)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM