【问题标题】:How to create a dictionary of series with an index from a dataframe in python如何从python中的数据框创建带有索引的系列字典
【发布时间】:2022-01-14 07:53:04
【问题描述】:

我有以下数据框

df = pd.DataFrame({'col_1': ['Animal','Deer','Sheep','Fish','Vehicle','Truck','Car','Mineral','Gold','Silver'], 
                   'col_2': ['Animal',0.5,0.25,0.25,'Vehicle',0.5,0.5,'Mineral',0.75,0.25],
                   'Group': [0,0,0,0,1,1,1,2,2,2]})

我想创建一个系列字典。我希望第 1 列是索引,第 2 列是值和组来指定系列。例如,第一个系列的名称(键)是“Animal”,它应该看起来像:


我尝试了以下方法。但这不对,我得到的是数据帧字典而不是系列,并且标题在第一行。

dict_of_series = {i: df.loc[df.group == i, ['col_1', 'col_2']] for i in range(1, df.group.iat[-1])} 

【问题讨论】:

  • 你能把你的预期输出吗

标签: python pandas series dictionary-comprehension


【解决方案1】:

loop by groupby objectDataFrame.set_axis 使用字典理解,按每个组的第一行设置列名,通过在DataFrame.iloc 中的索引删除第一行和最后一列,最后在DataFrame.rename_axis 中删除列名:

dict_of_series = {g['col_2'].iat[0]: 
                  g.set_axis(g.iloc[0], axis=1).iloc[1:, :-1].rename_axis(None, axis=1) 
                  for i, g in df.groupby('Group')} 


print (dict_of_series['Animal'])
  Animal Animal
1   Deer    0.5
2  Sheep   0.25
3   Fish   0.25

print (dict_of_series['Vehicle'])
  Vehicle Vehicle
5   Truck     0.5
6     Car     0.5

print (dict_of_series['Mineral'])
  Mineral Mineral
8    Gold    0.75
9  Silver    0.25

对于系列,在解决方案之前使用DataFrame.set_index,并将选择最后一列的iloc 更改为Series 和最后一个Series.rename_axis

df = df.set_index('col_1')

dict_of_series = {g['col_2'].iat[0]: 
                  g.set_axis(g.iloc[0], axis=1).iloc[1:, 0].rename_axis(None)
                  for i, g in df.groupby('Group')} 


print (dict_of_series['Animal'])
Deer      0.5
Sheep    0.25
Fish     0.25
Name: Animal, dtype: object

【讨论】:

  • 完美,你能帮我理解字典理解吗?例如,"i, g in df.groupby('Group')" 是做什么的? python如何知道什么是i,什么是g?我习惯于在 groupby 的末尾放置一个聚合器。
  • 这是一个数据框字典,我正在寻找一个系列字典。如何将第一列移到理解中的索引?
  • @JonathanHay - 你是对的,描述丢失了。还添加到答案以生成类似需要的系列。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-02-05
  • 2021-11-24
  • 2018-02-26
  • 1970-01-01
  • 2016-05-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多