[英]Add values to bottom of DataFrame automatically with Pandas
我正在初始化一个DataFrame:
columns = ['Thing','Time']
df_new = pd.DataFrame(columns=columns)
然后像这样向它写入值:
for t in df.Thing.unique():
df_temp = df[df['Thing'] == t] #filtering the df
df_new.loc[counter,'Thing'] = t #writing the filter value to df_new
df_new.loc[counter,'Time'] = dftemp['delta'].sum(axis=0) #summing and adding that value to the df_new
counter += 1 #increment the row index
有没有更好的方法可以在不使用'counter'显式增加行索引的情况下每次向数据帧添加新值?
如果我正确地解释了这一点,我认为这可以一行完成:
newDf = df.groupby('Thing')['delta'].sum().reset_index()
通过按“事物”分组,您可以从for循环中获得各种“ t过滤器”。 然后,我们将sum()
应用于“ delta”,但仅在各种“ t过滤”组中。 在这一点上,数据帧具有各种值“ t”作为索引,而“ t过滤后的增量”之和作为相应的列。 为了获得所需的输出,我们然后通过reset_index()
将“ t”插入其自己的列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.