我有很多个月的数据,每个月有很多个点,我需要计算特定年份中column1中的0与column2中的1出现了多少次,除以该年中column1中0出现的次数。 简单的例子:
temp = pd.DataFrame({'month':pd.date_range(start='2017-01-01', end='2019-01-01')})
temp['col1'] = np.random.randint(3, size=len(temp))
temp['col2'] = np.random.randint(3, size=len(temp))
我得到的最大值是column1和column2中的不同值对在不同年份一起出现的次数:
temp2 = temp.groupby(pd.Grouper(key='month', freq='A')).apply(lambda x: x.groupby('col1')['col2'].value_counts())
最佳答案
我认为您想要这样做:
temp['year'] = temp.month.apply(lambda x : x.year)
temp['condition'] = temp.apply(lambda row : ((row['col1'] == 0) and (row['col2'] == 1))*1,
axis=1)
output = temp.groupby('year').apply(lambda df : \
(df.condition.sum())/(df.col1.apply(lambda x: (x==0)*1).sum()))
关于python - 两列中基于年度的值比例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58536722/