将 pandas 数据框转换为字典,其中一列作为键,另一列作为多个值

Convert a pandas dataframe to dictionary with one column as key and other column as multiple values

我想将此数据框转换为字典,其中对于一个标签作为键,我将多个推文存储为值。有人可以帮忙吗?

假设您的数据框的变量名称是“df”,那么以下内容可能会有所帮助:

temp = df.groupby(['labels']).apply(lambda x: x['tweets'].tolist()).to_dict()
print(temp)

要获得预期结果,您可以 运行 例如:

result = df.groupby('labels')['tweets'].apply(list).to_dict()

详情:

  1. df.groupby('labels') - 对源行进行分组。
  2. ['tweets'] - 仅采用 tweets 列(来自每个组)。
  3. apply(list) - 将当前组中的推文转换为列表。 您甚至不需要使用任何明确的 lambda 函数。 到目前为止(groupbyapply的结果)是pandasonic Series.
  4. to_dict() - 将此 Series 转换为字典。

对于您的源数据(缩短了一点),结果是:

{'EXP': ['if you missed', 'the emotional'],
 'QUE': ['the neverending'],
 'STM': ['katie couric', 'a yearold nigerian']}