Pep*_*lac 5 python pandas pandas-groupby
我必须遵循df:
Col1 Col2
test Something
test2 Something
test3 Something
test Something
test2 Something
test5 Something
Run Code Online (Sandbox Code Playgroud)
我想得到
Col1 Col2 Occur
test Something 2
test2 Something 2
test3 Something 1
test Something 2
test2 Something 2
test5 Something 1
Run Code Online (Sandbox Code Playgroud)
我尝试使用:
df["Occur"] = df["Col1"].value_counts()
Run Code Online (Sandbox Code Playgroud)
但这没有帮助。我的“发生”列充满了“ NaN”
groupby关于“COL1”,然后应用transform上Col2返回了一系列的指数对准原来的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
Run Code Online (Sandbox Code Playgroud)
您还可以将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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3583 次 |
| 最近记录: |