簡體   English   中英

計算熊貓中的列值

[英]counting column values in pandas

dictionary = {'Year': [1985, 1985, 1986, 1986, 1987, 1987, 1987]}
pdf = pd.DataFrame(dictionary)

    Year
0   1985
1   1985
2   1986
3   1986
4   1987
5   1987
6   1987

我有一個名為pdf new data frame ,我需要按以下格式形成一個new data frame

Year   count
1985     2
1986     2 
1987     3

如何在熊貓中有效地做到這一點?

.value_counts

pdf['Year'].value_counts()

這是答案:

dictionary = {'Year': [1985, 1985, 1986, 1986, 1987, 1987, 1987]}
pdf = pd.DataFrame(dictionary)
gb = pdf.groupby('Year')['Year'].count()

Counter是一個計數器工具,用於支持方便快捷地對字典和其他可散列對象進行計數。

from collections import Counter

df = pd.DataFrame(Counter(pd.DataFrame(dictionary).Year).items(), 
                  columns=['Year', 'Count'])

>>> print df
print(df)
   Year  Count
0  1985      2
1  1986      2
2  1987      3

%timeit pd.DataFrame(dictionary).groupby('Year')['Year'].count()
1000 loops, best of 3: 777 µs per loop

%timeit pd.DataFrame(Counter(pd.DataFrame(dictionary).Year).items(), columns=['Year', 'Count'])
1000 loops, best of 3: 672 µs per loop

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM