Pandas Dataframe to_dict()以唯一列值作为键

时间:2016-03-24 21:12:23

标签: python pandas dataframe

df = pd.DataFrame({'A': ['jars', 'used'], 'B': ['Phrase', 'Phrase']})

      A       B
0  jars  Phrase
1  used  Phrase

期望的输出:

{'Phrase': ['jars', 'used']}

如果列B有多个唯一值(例如:唯一值为BroadPhraseExact):

{'Phrase': ['jars', 'used'], 'Exact': ['val1', 'val2'], 'Broad': ['cat', 'dog']}

我在想这样的事情,但A是关键。

df.set_index('B').to_dict('list')

{'A': ['jars', 'used']}

我试过了:

>>> dict([(b,[a]) for b, a in zip(df.B, df.A)])
{'Phrase': ['used']}

>>> [{b:[a]} for b, a in zip(df.B, df.A)]
[{'Phrase': ['jars']}, {'Phrase': ['used']}]

>>> df.set_index('B').T.to_dict('list')
{'Phrase': ['used']}

这可能是愚蠢的简单。

2 个答案:

答案 0 :(得分:2)

In [11]: df.groupby('B').agg({'A': lambda x: x.tolist()})['A'].to_dict()
Out[11]: {'Phrase': ['jars', 'used']}

答案 1 :(得分:1)

df = pd.DataFrame({'A': ['jars', 'used', 'fun', 'what', 'when'],
           'B': ['Phrase', 'Phrase', 'Exact', 'Exact', 'Broad']},
          columns=['A', 'B'])
df
      A       B
0  jars  Phrase
1  used  Phrase
2   fun   Exact
3  what   Exact
4  when   Broad

使用apply代替agg的另一种方式:

df.groupby('B').apply(lambda f: f['A'].values.tolist()).to_dict()

返回:

{'Broad': ['when'], 'Exact': ['fun', 'what'], 'Phrase': ['jars', 'used']}
相关问题