简体   繁体   English

如何对 pandas 中的值进行分组,但使用列表作为索引?

[英]How to groupby values in pandas but using lists as an index?

I have dataframe like and i need to groupby it based on fruit and value but i need to index it based on lists我有 dataframe 之类的,我需要根据水果和价值对其进行分组,但我需要根据列表对其进行索引

  Date       ID     Age      Value        Fruits
  1.1.19     1      50         2            Apple
  2.1.19     1      50         5            Mango
  2.1.19     1      50         8            Orange
  1.1.19     2      75         6            Grapes
  4.1.19     3      20         1            Apple
  4.1.19     3      20         0            Grapes

for example i have two lists:例如我有两个列表:

fruits_list = ['Apple', 'Mango', 'Orange', 'Grapes', 'Banana', 'Guava']
date_list = ['1.1.19', '2.1.19', '3.1.19', '4.1.19', '5.1.19', '6.1.19']

So if i use this:所以如果我使用这个:

df_filter.groupby(['Fruits', 'Date'])['Value'].mean().unstack().reset_index().fillna(0).round()

how it will be possible to use lists to re_index?如何使用列表来重新索引? There are more values list like Banana and Guava so i would like that also as in index还有更多值列表,例如香蕉和番石榴,所以我也希望索引中的值

Fix your code with reindex使用reindex修复您的代码

df.groupby(['Fruits', 'Date'])['Value'].mean().unstack(fill_value=0).\
    reindex(columns=date_list,index=fruits_list,fill_value=0).\
     round().reset_index()
Out[172]: 
Date  Fruits  1.1.19  2.1.19  3.1.19  4.1.19  5.1.19  6.1.19
0      Apple       2       0       0       1       0       0
1      Mango       0       5       0       0       0       0
2     Orange       0       8       0       0       0       0
3     Grapes       6       0       0       0       0       0
4     Banana       0       0       0       0       0       0
5      Guava       0       0       0       0       0       0

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

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