Python sum with condition使用日期和条件

2024-10-04 09:31:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要数据帧,我用的是熊猫。 我想从一个可变日期到一列中的值做一个累计和

我想在df2中添加第二列来显示日期,以便知道df2中date2之后AVG列的和大于100的日期。在

例如,df1和df2是我开始的数据帧,df3是我想要的,df3['date100']是平均值总和大于100的那一天:

df1 = pd.DataFrame({'date1': ['1/1/2014', '2/1/2014', '3/1/2014','1/1/2014', '2/1/2014', '3/1/2014','1/1/2014', '2/1/2014', '3/1/2014'],
 'Place':['A','A','A','B','B','B','C','C','C'],'AVG': [62,14,47,25,74,60,78,27,41]})

df2 = pd.DataFrame({'date2': ['1/1/2014', '2/1/2014'], 'Place':['A','C'])})

*Something*
df3 = pd.DataFrame({'date2': ['1/1/2014', '2/1/2014'], 'Place':['A','C'], 'date100': ['3/1/2014', '2/1/2014'], 'sum': [123, 105]})

我找到了一些答案,但大多数都使用groupby,而df2没有分组。在


Tags: 数据dataframeplacesomethingavg平均值pddf1
2条回答

因为你的例子非常基础,如果你有边缘案例,你想让我处理,只要问。此解决方案意味着:

解决方案:

#   For this solution your DataFrame needs to be sorted by date.
limit = 100
df = pd.DataFrame({
    'date1': ['1/1/2014', '2/1/2014', '3/1/2014','1/1/2014',
              '2/1/2014', '3/1/2014','1/1/2014', '2/1/2014', '3/1/2014'], 
    'Place':['A','A','A','B','B','B','C','C','C'],
    'AVG': [62,14,47,25,74,60,78,27,41]})

df2 = pd.DataFrame({'date2': ['1/1/2014', '2/1/2014'], 'Place':['A','C']})

result = []
for row in df2.to_dict('records'):
    #   For each date, I want to select the date that comes AFTER this one.
    #   Then, I take the .cumsum(), because it's the agg you wish to do.
    #   Filter by your limit and take the first occurrence.
    #   Converting this to a dict, appending it to a list, makes it easy
    #   to rebuild a DataFrame later.
    ndf = df.loc[ (df['date1'] >= row['date2']) & (df['Place'] == row['Place']) ]\
            .sort_values(by='date1')
    ndf['avgsum'] = ndf['AVG'].cumsum()
    final_df = ndf.loc[ ndf['avgsum'] >= limit ]

    #   Error handling, in case there is not avgsum above the threshold.
    try:
        final_df = final_df.iloc[0][['date1', 'avgsum']].rename({'date1' : 'date100'})
        result.append( final_df.to_dict() )
    except IndexError:
        continue

df3 = pd.DataFrame(result)

final_df = pd.concat([df2, df3], axis=1, sort=False)
print(final_df)
#       date2 Place  avgsum   date100
# 0  1/1/2014     A   123.0  3/1/2014
# 1  2/1/2014     C     NaN       NaN

这是一个直接的解决方案,假设如下:

  • df1按日期排序
  • df2中的每个日期都存在一个解决方案

然后可以执行以下操作:

df2 = df2.join(pd.concat([
        pd.DataFrame(pd.DataFrame(df1.loc[df1.date1 >= d].AVG.cumsum()).query('AVG>=100')
                .iloc[0]).transpose()
        for d in df2.date2]).rename_axis('ix').reset_index())\
    .join(df1.drop(columns='AVG'), on='ix').rename(columns={'AVG': 'sum', 'date1': 'date100'})\
    .drop(columns='ix')[['date2', 'date100', 'sum']]

这将执行以下操作:

  • 对于df2中的每个日期,找到第一个平均值至少为100的日期
  • 将结果合并到一个由df1中该行的索引索引索引的单个数据帧中
  • 将该索引存储在ix列中,并重置该索引以将该数据帧连接到df2
  • 使用ix列将其连接到df1减去AVG
  • 重命名这些列,删除ix列,然后重新排列所有内容

相关问题 更多 >