Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为数据帧中的每个变量x计算变量y,并添加相对频率_Python_Pandas_Dataframe_Count - Fatal编程技术网

Python 为数据帧中的每个变量x计算变量y,并添加相对频率

Python 为数据帧中的每个变量x计算变量y,并添加相对频率,python,pandas,dataframe,count,Python,Pandas,Dataframe,Count,我有: df=pd.DataFrame({“A”:[[55218],[55218],[55218],[55222],“B”:[[0],[0],[2],[1]}) 我希望在“A”中55218每0、1或2计数一次,并返回相对频率 我的预期产出是: df_new=pd.DataFrame({“A”:[[55218]、[55218]、[55218]、[55222]、“B”:[[0]、[0]、[2]、[1]、“Count”:[[2]、[2]、[1]、[1]、“rel_frequeru:[0.67]、[0

我有:

df=pd.DataFrame({“A”:[[55218],[55218],[55218],[55222],“B”:[[0],[0],[2],[1]})
我希望在“A”中55218每0、1或2计数一次,并返回相对频率

我的预期产出是:

df_new=pd.DataFrame({“A”:[[55218]、[55218]、[55218]、[55222]、“B”:[[0]、[0]、[2]、[1]、“Count”:[[2]、[2]、[1]、[1]、“rel_frequeru:[0.67]、[0.67]、[0.33]、[1]})
使用列,然后将列除以
A
的映射频率和:


我想你需要
df['count']=df.groupby(['A','B'])['A'].transform('size')
如何解决这个问题?我想这是可行的,谢谢
df['Count'] = df.groupby(['A','B'])['A'].transform('size')
df['rel_frequ'] = df['Count'].div(df['A'].map(df['A'].value_counts()))
print (df)
       A  B  Count  rel_frequ
0  55218  0      2   0.666667
1  55218  0      2   0.666667
2  55218  2      1   0.333333
3  55222  1      1   1.000000