一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

pandas实现某一列分组其他列合并成list代码示例

时间:2022-06-25 02:10:09 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下pandas实现某一列分组其他列合并成list代码示例,文章介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

pandas列转换为字典,但将相同第一列(键)的所有值合并为一个键

形式一:

import pandas as pd 
# data
data = pd.DataFrame({'column1':['key1','key1','key2','key2'],
    'column2':['value1','value2','value3','value3']})
print(data) 
# Grouped dict
data_dict = data.groupby('column1').column2.apply(list).to_dict() 
print(data_dict)

输出结果:

 column1 column2
0  key1 value1
1  key1 value2
2  key2 value3
3  key2 value3 
{'key1': ['value1', 'value2'], 'key2': ['value3', 'value3']}

形式二:

import pandas as pd
# data
df = pd.DataFrame({'column1':['key1','key1','key2','key2'],
    'column2':['value1','value2','value1','value2'],
    'column3':['value11','value11','value22','value22'],
    'column4':['value44','value44','value55','value55']}) 
# Grouped dict
data_dict = df.groupby('column1').apply(lambda x: {col:x[col].tolist() for col in x.columns if col != 'column2'}).to_dict()
print(data_dict) 
data_dict2 = df.groupby('column1').apply(lambda x: {col:x[col].tolist()[0] if col != 'column2' else x[col].tolist() for col in x.columns}).to_dict()
print(data_dict2)

输出结果:

#data_dict
{
  'key1': {
    'column1': ['key1', 'key1'], 
    'column3': ['value11', 'value11'], 
    'column4': ['value44', 'value44']
  }, 
  'key2': {
    'column1': ['key2', 'key2'], 
    'column3': ['value22', 'value22'], 
    'column4': ['value55', 'value55']
  }
}
#data_dict2
{
  'key1': {
    'column1': 'key1', 
    'column2': ['value1', 'value2'], 
    'column3': 'value11', 
    'column4': 'value44'
  }, 
  'key2': {
    'column1': 'key2', 
    'column2': ['value1', 'value2'], 
    'column3': 'value22', 
    'column4': 'value55'
  }
}

热门栏目