简体   繁体   English

对列中的多个值进行分组

[英]groupby multiple values in a column

I have a subset of a dataframe here:我在这里有一个 dataframe 的子集:

data = {'Name': ['ch1', 'ch2', 'ch3', 'ch4', 'ch5', 'ch6'],
        'Time': [1,2,3,4,5,6],
        'Week' : [1, 2, 3, 2, 3, 2]
            }

dfx = pd.DataFrame(data)

I need to sum up all the times for each week so Week 1 time is 1, Week 2 time is 2+4+6, and Week 3 is 3+5.我需要总结每周的所有时间,所以第 1 周时间是 1,第 2 周时间是 2+4+6,第 3 周时间是 3+5。 I also need it to look through the 'Week' column and find all the different weeks, so for this example there are 3 but for another dataframe it could be 2 or 4.我还需要它来查看“周”列并找到所有不同的周,因此对于此示例,有 3 个,但对于另一个 dataframe,它可能是 2 或 4。

End result is look through a column in a dataframe, find the unique values (1,2,3,...n), groupby be each of those values into rows and sum up the time for each of those values.最终结果是查看 dataframe 中的一列,找到唯一值 (1,2,3,...n),将这些值中的每一个分组到行中,并将每个值的时间相加。

I have tried a handful of ways but nothing is really working how I would like.我尝试了几种方法,但没有什么能真正按照我的意愿工作。 I appreciate any help or ideas.我感谢任何帮助或想法。

Expected Output:预期 Output:

                                 Sum
Week 1: 1                         1
Week 2: 2  4  6                   12
Week 3: 3  5                      8

The output can be either individual dataframes of the data or one dataframe that has all three rows with all the numbers and the sum at the end. output 可以是数据的单个数据帧,也可以是一个 dataframe,所有三行都包含所有数字和总和。

    import pandas as pd
data = {'Name': ['ch1', 'ch2', 'ch3', 'ch4', 'ch5', 'ch6'],
        'Time': [1,2,3,4,5,6],
        'Week' : [1, 2, 3, 2, 3, 2]
            }

dfx = pd.DataFrame(data)
dfx = dfx.groupby('Week')['Time'].sum()
print(dfx)

output: output:

Week
1     1
2    12
3     8

You can groupby "Week", select column "Time", and you can pass multiple functions (such as list constructor and sum ) to Groupby.agg to do the things you want:您可以groupby "Week", select column "Time",并且可以将多个函数(例如list构造函数和sum )传递给Groupby.agg来做你想做的事情:

out = dfx.groupby('Week')['Time'].agg(Times=list, Total=sum)

Output: Output:

          Times  Total
Week                  
1           [1]      1
2     [2, 4, 6]     12
3        [3, 5]      8

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

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