12

我必须关注df:

Col1    Col2
test    Something
test2   Something
test3   Something
test    Something
test2   Something
test5   Something

我想得到

Col1    Col2          Occur
test    Something     2
test2   Something     2
test3   Something     1
test    Something     2
test2   Something     2
test5   Something     1

我试过使用:

df["Occur"] = df["Col1"].value_counts()

但这没有帮助。我有一个充满“NaN”的 Occur 列

4

3 回答 3

7

您还可以将GroupBy+transform与 一起使用size

df['Occur'] = df.groupby('Col1')['Col1'].transform('size')

print(df)

    Col1       Col2  Occur
0   test  Something      2
1  test2  Something      2
2  test3  Something      1
3   test  Something      2
4  test2  Something      2
5  test5  Something      1
于 2018-09-10T09:41:09.970 回答
5

groupbyon 'col1' 然后应用transformonCol2返回一个 Series,其索引与原始 df 对齐,因此您可以将其添加为列:

In [3]:
df['Occur'] = df.groupby('Col1')['Col2'].transform(pd.Series.value_counts)
df

Out[3]:
    Col1       Col2 Occur
0   test  Something     2
1  test2  Something     2
2  test3  Something     1
3   test  Something     2
4  test2  Something     2
5  test5  Something     1
于 2016-05-06T17:08:00.673 回答
0

当我想保留更多列而不仅仅是 Col1 和 Col2 两列时,我无法获得其他答案。下面对我来说很好,保留了任何数量的其他列。

df['Occur'] = df['Col1'].apply(lambda x: (df['Col1'] == x).sum())
于 2020-07-15T08:02:22.563 回答