pandas 对dataframe值求和并合并到具有求和值的1索引中[重复]

jobtbby3  于 2023-09-29  发布在  其他
关注(0)|答案(1)|浏览(103)

此问题已在此处有答案

Calculate daily sums using pandas(2个答案)
16天前关闭
我有一个数据框

datetime           cnt
1     2015-01-04 00:00:00  102                      datetime   cnt
2     2015-01-04 01:00:00  23     Turns into  1    2015-01-04  170
3     2015-01-04 02:00:00  45

datetime = datetime,cnt = bicycles rent this day in this hour我想把这样的3个索引在1个索引,有datetime没有小时,并总结了cnt。
并且只能合并同一天但不同时间发生的索引

path2 = r'C:\Users\bossd\OneDrive\Документы\zhopa123.csv'
df2 = pd.read_csv(path2) 
col2015 = df2.loc[df2['year'] == 2015]
a = col2015['cnt']
b = col2015['timestamp']

我尝试了这个算法来合并两个索引并将它们的cnt值相加,但是没有成功

for k in len(df2+1):
    if (df2.loc[k, 'timestamp']).date() == (df2.loc[k+1, 'timestamp']).date():
        df2.loc[df2.index[k], 'cnt'] + df2.loc[df2.index[k+1], 'cnt']
        df2.drop(df2.index[k+1])
    elif (df2.loc[k, 'timestamp']).date() != (df2.loc[k+1, 'timestamp']).date():
        pass

我得到一个错误TypeError: can only concatenate str (not "int") to str
The dataframe i have

pw9qyyiw

pw9qyyiw1#

IIUC,可以使用.groupby

df = df.groupby(df["datetime"].dt.date)["cnt"].sum().reset_index()

print(df)

图纸:

datetime  cnt
0  2015-01-04  170

编辑:

  • .dt.date返回datetime Series中的日期部分。
  • Series.reset_index()从Series创建一个嵌套框架(索引是date,现在它是一个列,嵌套框架有新的索引-从0开始)

相关问题