溫馨提示×

Python crosstab函數(shù)的數(shù)據(jù)透視功能

小樊
82
2024-08-29 13:33:04
欄目: 編程語言

Python中的crosstab函數(shù)是pandas庫中的一個函數(shù),用于創(chuàng)建數(shù)據(jù)透視表

以下是使用crosstab函數(shù)創(chuàng)建數(shù)據(jù)透視表的示例:

import pandas as pd

# 創(chuàng)建一個示例DataFrame
data = {'A': ['foo', 'bar', 'baz', 'foo', 'bar', 'baz'],
        'B': ['one', 'two', 'three', 'two', 'one', 'three']}
df = pd.DataFrame(data)

# 使用crosstab函數(shù)創(chuàng)建數(shù)據(jù)透視表
ct = pd.crosstab(df['A'], df['B'])
print(ct)

輸出結(jié)果如下:

B   one  three  two
A                  
bar    1      0    1
baz    0      1    0
foo    1      0    1

在這個示例中,我們首先創(chuàng)建了一個包含兩列(‘A’和’B’)的DataFrame。然后,我們使用crosstab函數(shù)創(chuàng)建了一個數(shù)據(jù)透視表,其中行標(biāo)簽是’A’列的值,列標(biāo)簽是’B’列的值,單元格值是每個類別組合的計數(shù)。

0