如何在Python中使用NumPy按年求和

icnyk63a  于 2022-12-26  发布在  Python
关注(0)|答案(1)|浏览(163)

如果我有这样的数据:

2012 $20,000
2012 $20,000
2013 $10,000
2014 $10,000
2014 $10,000

如何显示[40000,10000,20000]的数据数组,其中的数据将按年聚合?
第一个月

wxclj1h5

wxclj1h51#

假设您的数据采用此格式..!

year    income
0   2012    $20,000
1   2012    $20,000
2   2013    $10,000
3   2014    $10,000
4   2014    $10,000
    • 代码:-**
import pandas as pd
df1=pd.read_csv('/content/Untitled spreadsheet - Sheet1.csv')
df1['income'] = df1['income'].replace({'\$': '', ',': ''}, regex=True)
df1['income'] = df1['income'].astype(int)
df2=df1.groupby(df1['year']).sum()
print(df2) 
lis=[]
for aggregate in df2['income']:
  lis.append(aggregate)
print(lis)
    • 输出:-**

第一个月

income
year        
2012   40000
2013   10000
2014   20000

print(lis)

[40000, 10000, 20000]

相关问题