我有一长串元组,我需要排序,例如.[('12/2010',196.9876),('12/2010',654.9876),('11/2010',234.9876).........]

use*_*635 3 python tuples list pandas-groupby

我有一长串元组,我需要排序,例如. [('11/2010', 196.9876),('11/2010', 654.9876), ('12/2010', 234.9876).........]

我想使用日期(第一个元素)将元组中的第二个元素分组到单独的列表中.到目前为止,我已经获得了一个单独的列表,例如[11/2010,12/2010....]我正在尝试使用这些列表来引用更大的列表并进行数学计算,我想出了:

vol_new = []
for monthrow in unique_date_list: 
    for row in date_and_av_tup: 
        if monthrow == row[0]:
            vol_new.append(row[1])
            len_vol_new = len(vol_new) # finds the n of items in volume list
            my_vol_total_new = reduce(lambda y,x: x+y, vol_new) # adds everything in the volume list
            average_vol_new = float(my_vol_total_new) / float(len_vol_new) #stores the average volume in a list

print average_vol_new
Run Code Online (Sandbox Code Playgroud)

这可能是非常垃圾的代码,但我是编码的新手,并且在尝试这样做时非常沮丧,感谢您提供的任何帮助.

PS我正在使用Python

Mat*_*ohn 6

您可能会发现pandas数据分析库对此非常有用,可以创建一个可以轻松执行这些功能的表.例如:

import pandas as pd

months = [('11/2010', 196.9876),('11/2010', 654.9876), ('12/2010', 234.9876)]
df = pd.DataFrame(months, columns=['Month', 'Value'])
Run Code Online (Sandbox Code Playgroud)

df是一个DataFrame(即表),看起来像:

    Month   Value
0    11/2010     196.9876
1    11/2010     654.9876
2    12/2010     234.9876
Run Code Online (Sandbox Code Playgroud)

您可以使用groupby以下方法获取平均值和总数:

[7]:  df.groupby('Month').mean()
Out[7]:         Value    
        Month   
        11/2010  425.9876
        12/2010  234.9876

In [8]: df.groupby('Month').sum()
Out[8]:          Value
        Month   
        11/2010  851.9752
        12/2010  234.9876
Run Code Online (Sandbox Code Playgroud)