python - 两列中基于年度的值比例

标签 python pandas

我有很多个月的数据,每个月有很多个点,我需要计算特定年份中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/

相关文章:

python - 从 Pandas DataFrame 计算 IDF

python - 在 Pandas 中按条件分配值(value)的最佳方式

python - 在 matplotlib 中使用三角剖分时如何处理在我的几何边缘之间形成的(不需要的)三角形

python - Selenium XPath "[@value]"与值不匹配的元素

python - 在 Django 上更改 ModelChoiceField 的查询集

python - 如何设置我创建的任何 Vim 文件默认附加 #!/usr/bin/env python

python - 删除一列中的 char/str 作为从另一列中删除不同 str 的条件 - DF Pandas

python - 为 boto3 SQS 设置端点

Python/Pandas : How to select a cell value, 在同一行中给出 2 个值?

python - 如何确定将哪些列设置为 Pandas DataFrame 中的索引?