1 回答
TA贡献1830条经验 获得超3个赞
import pandas as pd
# Creating the dictionary
dic = {'ID': [1,1,1,2,2,2,3,3,3,3], 'Tell': ['Yes', 'Yes', 'No', 'Yes','Yes', 'No','Yes', 'Yes','No', 'Yes'], 'Number': [3,6,9,4,7,8,15,8,6,13]}
# Creating the dataframe
df = pd.DataFrame(dic)
df = (pd.merge(left=df, right=df[df.Tell == 'Yes'].groupby('ID')['Number'].mean(), on='ID')
.rename(columns={'Number_x':'Number', 'Number_y':'mean'}))
print(df)
印刷:
ID Tell Number mean
0 1 Yes 3 4.5
1 1 Yes 6 4.5
2 1 No 9 4.5
3 2 Yes 4 5.5
4 2 Yes 7 5.5
5 2 No 8 5.5
6 3 Yes 15 12.0
7 3 Yes 8 12.0
8 3 No 6 12.0
9 3 Yes 13 12.0
添加回答
举报