Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.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 在另一列中的值相似的列中计算值的频率_Python_Pandas_Count_Frequency - Fatal编程技术网

Python 在另一列中的值相似的列中计算值的频率

Python 在另一列中的值相似的列中计算值的频率,python,pandas,count,frequency,Python,Pandas,Count,Frequency,给定一个如下列a和列b的数据帧。如何构造两个附加列,一个用于计算所有列的列_a中每个值的频率,另一个用于计算列_a中的值相同的唯一值数: column_a | column_b | col_a_count | count_unique_b_where_a 0 1 4 3 0 1 4 3 0 2 4 3 0

给定一个如下列a和列b的数据帧。如何构造两个附加列,一个用于计算所有列的列_a中每个值的频率,另一个用于计算列_a中的值相同的唯一值数:

column_a | column_b | col_a_count | count_unique_b_where_a
  0           1           4         3
  0           1           4         3
  0           2           4         3
  0           3           4         3
  2           0           3         1
  2           0           3         1
  2           0           3         1 
  5           3           1         1
  9           5           6         5 
  9           5           6         5
  9           3           6         5
  9           4           6         5
  9           2           6         5
  9           1           6         5
使用groupby和agg:

使用groupby和agg:

s = (df.groupby('column_a').agg(
        {'column_a': 'count', 'column_b': 'nunique'}).reindex(df.column_a))
          column_a  column_b   
column_a                       
0                4         3   
0                4         3   
0                4         3   
0                4         3   
2                3         1   
2                3         1   
2                3         1   
5                1         1   
9                6         5   
9                6         5   
9                6         5   
9                6         5   
9                6         5   
9                6         5