簡體   English   中英

Python Pandas 計算特定值的出現次數

[英]Python Pandas Counting the Occurrences of a Specific value

我試圖找出某個值在一列中出現的次數。

我用data = pd.DataFrame.from_csv('data/DataSet2.csv')制作了 dataframe

現在我想知道某些東西在列中出現的次數。 這是怎么做到的?

我以為是下面,我在教育欄目中查找並計算時間的地方? 發生。

下面的代碼顯示我正在嘗試查找9th次出現的次數,錯誤是我在運行代碼時得到的

代碼

missing2 = df.education.value_counts()['9th']
print(missing2)

錯誤

KeyError: '9th'

您可以根據您的條件創建數據subset ,然后使用shapelen

print df
  col1 education
0    a       9th
1    b       9th
2    c       8th

print df.education == '9th'
0     True
1     True
2    False
Name: education, dtype: bool

print df[df.education == '9th']
  col1 education
0    a       9th
1    b       9th

print df[df.education == '9th'].shape[0]
2
print len(df[df['education'] == '9th'])
2

性能很有趣,最快的解決方案是比較 numpy array 和sum

圖形

代碼

import perfplot, string
np.random.seed(123)


def shape(df):
    return df[df.education == 'a'].shape[0]

def len_df(df):
    return len(df[df['education'] == 'a'])

def query_count(df):
    return df.query('education == "a"').education.count()

def sum_mask(df):
    return (df.education == 'a').sum()

def sum_mask_numpy(df):
    return (df.education.values == 'a').sum()

def make_df(n):
    L = list(string.ascii_letters)
    df = pd.DataFrame(np.random.choice(L, size=n), columns=['education'])
    return df

perfplot.show(
    setup=make_df,
    kernels=[shape, len_df, query_count, sum_mask, sum_mask_numpy],
    n_range=[2**k for k in range(2, 25)],
    logx=True,
    logy=True,
    equality_check=False, 
    xlabel='len(df)')

使用countsum的幾種方法

In [338]: df
Out[338]:
  col1 education
0    a       9th
1    b       9th
2    c       8th

In [335]: df.loc[df.education == '9th', 'education'].count()
Out[335]: 2

In [336]: (df.education == '9th').sum()
Out[336]: 2

In [337]: df.query('education == "9th"').education.count()
Out[337]: 2

一種計算'?'出現的優雅方法或任何列中的任何符號,都是使用數據框對象的內置函數isin

假設我們已將“汽車”數據集加載到df對象中。 我們不知道哪些列包含缺失值( '?'符號),所以讓我們這樣做:

df.isin(['?']).sum(axis=0)

DataFrame.isin(values)官方文檔說:

它返回布爾數據幀,顯示數據幀中的每個元素是否包含在值中

請注意, isin接受一個可迭代對象作為輸入,因此我們需要將包含目標符號的列表傳遞給該函數。 df.isin(['?'])將返回一個布爾數據框,如下所示。

    symboling   normalized-losses   make    fuel-type   aspiration-ratio ...
0   False       True                False   False       False
1   False       True                False   False       False
2   False       True                False   False       False
3   False       False               False   False       False
4   False       False               False   False       False
5   False       True                False   False       False
...

為了計算每列中目標符號的出現次數,讓我們通過指示axis=0對上述數據幀的所有行sum 最終(截斷的)結果顯示了我們的期望:

symboling             0
normalized-losses    41
...
bore                  4
stroke                4
compression-ratio     0
horsepower            2
peak-rpm              2
city-mpg              0
highway-mpg           0
price                 4

嘗試這個:

(df[education]=='9th').sum()

簡單但效率不高:

list(df.education).count('9th')

要查找列的特定值,您可以使用下面的代碼

無論偏好如何,您都可以使用您喜歡的任何方法

df.col_name.value_counts().Value_you_are_looking_for

以泰坦尼克號數據集為例

df.Sex.value_counts().male

這給出了船上所有男性的計數雖然如果你想計算一個數字數據那么你不能使用上面的方法,因為 value_counts() 只用於系列類型的數據因此失敗所以你可以使用第二種方法示例

第二種方法是

#this is an example method of counting on a data frame
df[(df['Survived']==1)&(df['Sex']=='male')].counts()

這不像 value_counts() 那樣有效,但如果您想計算數據框的值肯定會有所幫助希望這有幫助

編輯——如果你想找一些中間有空格的東西

你可以使用

df.country.count('united states')我相信這應該可以解決問題

計算 Pandas 數據框中列中出現次數(唯一值)的簡單示例:

import pandas as pd

# URL to .csv file 
data_url = 'https://yoursite.com/Arrests.csv'
# Reading the data 
df = pd.read_csv(data_url, index_col=0)
# pandas count distinct values in column 
df['education'].value_counts()

輸出:

Education        47516 
9th              41164 
8th              25510 
7th              25198 
6th              25047                       
...  
3rd                 2 
2nd                 2 
1st                 2 
Name: name, Length: 190, dtype: int64

我認為這可能是一個更簡單的解決方案。 假設您有以下數據框。

DATE    LANG       POSTS

2008-07-01 c# 3 2008-08-01 assembly 8 2008-08-01 javascript 2 2008-08-01 c 85 2008-08-01 python 11 2008-07-01 c# 3 2008-08-01 assembly 8 2008 -08-01 javascript 62 2008-08-01 c 85 2008-08-01 python 14

你可以像這樣找到 LANG 項目總和的出現

df.groupby('LANG').sum()

您將獲得每種語言的總和

暫無
暫無

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

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