Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.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 - Fatal编程技术网

Python 熊猫:用多类标签的计数替换分类值

Python 熊猫:用多类标签的计数替换分类值,python,pandas,Python,Pandas,假设我有一个数据帧: df = pd.DataFrame({'label': [0, 1, 2, 0, 1, 2], 'cat_col': [1, 1, 2, 2, 3, 3]}) cat_col label 0 1 0 1 1 1 2 2 2 3 2 0 4 3 1 5 3 2 我想将此数据帧转换为以下内容: cat_col, label,

假设我有一个数据帧:

df = pd.DataFrame({'label': [0, 1, 2, 0, 1, 2], 'cat_col': [1, 1, 2, 2, 3, 3]})
   cat_col  label
0        1      0
1        1      1
2        2      2
3        2      0
4        3      1
5        3      2
我想将此数据帧转换为以下内容:

cat_col, label, count_when_label_is_0, count_when_label_is_1, count_when_label_is_2
1         0           1,               1,          0
1         1           1,               1,          0
...
因此,基本上我为每个标签值(多项式标签)添加一列,当row.cat_col是该行中的值时,我为每行添加该标签值的计数。我目前有这个,但速度很慢:

size = df[['cat_col', 'label']].groupby(['cat_col', 'label']).size()
def get_size(cat_val, label_val):
  if label_val in size[cat_val]: return size[cat_val][target_val]
    return 0

for label_val in range(9): # 9 classes in multinominal label
  df['new_col_' + str(label_val)] = df['cat_col'].apply(
      lambda cat_val: get_size(cat_val, label_val))
您可以使用:


虽然这与OPs不同,但作为一种变换(在cat_col上)来做这件事似乎很奇怪。。。
In [11]: df.pivot_table(index="cat_col", columns="label", aggfunc=len, fill_value=0)
Out[11]:
label    0  1  2
cat_col
1        1  1  0
2        1  0  1
3        0  1  1