如何计算所有列中特定行的值的频率

时间:2017-07-22 07:46:37

标签: python pandas

假设我有一个包含四列的数据框,其中部分内容如下:

<?php

abstract class AbstractFactory
{
    abstract public function createProduct(string $content);
}

class Factory extends AbstractFactory
{
    public function createProduct(string $content)
    {
        return new Product($content);
    }
}

class Product
{
    private $text;

    public function __construct(string $text)
    {
        $this->text = $text;
    }

    public function getText(){
        return $this->text;
    }
}


$factory = new Factory();
$product = $factory->createProduct('foobar');
echo $product ->getText();
?>

现在我想创建四个列,每个列对应于每个值的频率,考虑其他三列,如列将如下所示:

C1 C2 C3 C4
60 60 60 60
59 59 58 58
0  0  0  0
12 13 13 11 

在单元格1,1中,值为4,因为值60出现在特定行的所有列中。 在单元格4,1中,值为1,因为12出现在特定行的其他列中。 我需要在pandas数据框中计算并添加特征F1,F2,F3,F4。

1 个答案:

答案 0 :(得分:2)

使用apply axis=1按行mapvalue_counts的频率进行处理:

df = df.apply(lambda x: x.map(x.value_counts()),axis=1)
print (df)
   C1  C2  C3  C4
0   4   4   4   4
1   2   2   2   2
2   4   4   4   4
3   1   2   2   1