用另一列中重复值的数量填充一列



我有一个如下的df:

0.2
结果 妈妈
10/20 获胜者
10/20 获胜者 0.9
11/20 获胜者 0.6
11/20 获胜者 0.2
11/20 获胜者 0.9
10/20 失败者 0.6
10/20 失败者 0.2
10/20 失败者 0.9
11/20 失败者 0.6

假设您的原始DataFrame被称为df:,您可以使用此代码来实现您想要的目标

counts = df.groupby(['month', 'outcome'], as_index=False).count()
counts = counts.rename(columns={'mom.ret': 'q'})
# Use this line if you want the float value of the division 0.5
# counts['q'] = 1/counts['q']
# Use this line if you want the string '1/2'
counts['q'] = counts['q'].apply(lambda x: f'1/{x}')
result = pd.merge(df, counts)

结果如下:

month   outcome mom.ret q
0   10/20   winner  0.2 1/2
1   10/20   winner  0.9 1/2
2   11/20   winner  0.6 1/3
3   11/20   winner  0.2 1/3
4   11/20   winner  0.9 1/3
5   10/20   loser   0.6 1/2
6   10/20   loser   0.2 1/2
7   11/20   loser   0.9 1/2
8   11/20   loser   0.6 1/2

使用df['q'] = 1/df.groupby(['month', 'outcome']).transform('count')

更新答案:

@timgeb只需要一个月的groupby。为了输出分数而不是小数,我使用了方便的人性化库。

import humanize      # pip install humanize # if needed
df['q'] = 1 / df.groupby(['month', 'outcome'])['month'].transform('count')
df['q'] = df['q'].apply(lambda x : humanize.fractional(x))

请注意,不能只将.count()与groupby一起使用——您需要transform方法来返回与原始DataFrame长度相同的Series。

使用Python 3.9.7、pandas 1.4.1

制作原始df的代码(我省略了与之无关的mom.ret列(。

import pandas as pd
df = pd.DataFrame(
{
"month": [
"10/20",
"10/20",
"11/20",
"11/20",
"11/20",
"10/20",
"10/20",
"10/20",
"11/20",
],
"outcome": [
"winner",
"winner",
"winner",
"winner",
"winner",
"loser",
"loser",
"loser",
"loser",
],
}
)

最新更新