Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
121 views
in Technique[技术] by (71.8m points)

Capturing Pandas aggregation in to Lists

I have a column of data which has datetime and another column which has a numeric field (Length) and I am able to aggregate as below, where I am grouping by datetime and getting min/mean/max of all Lengths.

Code:

df.groupby(['DateTime']).agg({'Length': ['min', 'mean', 'max']})

Output:

                    Length                   
                            min         mean   max
DateTime                                          
2020-11-24 14:30:00         118  1172.712000  1505
2020-11-24 14:30:01         118  1246.719495  1508
2020-11-24 14:30:02         115  1062.351156  1508

I need a simple way to capture this output in a set of lists, something like this:

outputdatelist=[2020-11-24 14:30:00, 2020-11-24 14:30:01,...]
outputlen_min=[118, 118, 115]

Similarly for mean, max.

Is there a way to do it?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Lets say the input df is like below,

     DateTime  Length
0  2018-01-01     100
1  2018-02-01     100
2  2018-03-01     100
3  2018-04-01     100
4  2018-05-01     100

Try the code:

df1 = df.groupby(['DateTime']).agg({'Length': ['min', 'mean', 'max']}).reset_index()
outputdatelist = df1['DateTime'].tolist()
outputlen_min =  df1['Length']['min'].tolist()

Prints:

print(outputdatelist)
['2018-01-01', '2018-02-01', '2018-03-01', '2018-04-01', '2018-05-01']
print(outputlen_min)
[100, 100, 100, 100, 100]

similarly for mean and max columns.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...