[英]creating a pivot_table fails on a pandas dataframe
我有一個數據框,其中包含列year
, month
, source
,...每個(年,月,源)有多個記錄,並且我需要生成一個數據透視表,其索引為(年,月),源是列和計數每個(年,月,源)記錄中的值是值。 我有以下代碼
df.privot_table(index = ['year','month'], columns = ['source'], aggfunc = np.size, fill_value = 0)
這是我的數據的樣子
2001,02,A, ....
2001,02,A,....
2001,03,B,....
2001,03,B,....
2001,03,B,....
這就是我想要的數據
A B
2001, 02, 2, 0
2001, 03, 0, 3
但它引發以下錯誤信息
Reindexing only valid with uniquely values index objects
怎么了?
您可以使用aggfunc=len
獲得所需的輸出。
import pandas as pd
df = pd.DataFrame([[2001, '02', 'A'], [2001, '02', 'A'], [2001, '03', 'B'],
[2001, '03', 'B'], [2001, '03', 'B']],
columns=['Year', 'Month', 'Source'])
res = df.pivot_table(index=['Year', 'Month'], columns='Source',
aggfunc=len, fill_value=0)
print(res)
Source A B
Year Month
2001 02 2 0
03 0 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.