欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

pandas中的dataframe匯總和計算方法

 更新時間:2023年06月13日 10:03:14   作者:tsing_9521  
這篇文章主要介紹了pandas中的dataframe匯總和計算方法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

pandas dataframe匯總和計算方法

Dataframe匯總計算的主要方法有

在這里插入圖片描述

在這里插入圖片描述

Pandas 統(tǒng)計的一些常用方法 

1.frame.idxmax(): 列的最大值 輸出每列最大值的索引

np.random.seed(38754)
data=np.random.randint(0,15,15).reshape(5,3)
frame=DataFrame(data,index=['a','b','c','d','e'],columns=['x','y','z'])
result=frame.idxmax()
print(result)
#輸出:
x    b
y    a
z    e

2.frame.cumsum() :返回行或列的累加值的series,默認列累加

語法:

DataFrame.cumsum(axis=None, dtype=None, out=None, skipna=True, **kwargs)
  • axis=0: 行 axis=1:列(默認)
  • skipna:是否跳過空值,默認為True
np.random.seed(38754)
data=np.random.randint(0,15,15).reshape(5,3)
frame=DataFrame(data,index=['a','b','c','d','e'],columns=['x','y','z'])
result=frame.cumsum(axis=1)
print(frame)
print(result)
#輸出:
    x   y   z
a   5  14   7
b  12  12   6
c   3   7   8
d  11  10   0
e   1  10  10
    x   y   z
a   5  19  26
b  12  24  30
c   3  10  18
d  11  21  21
e   1  11  21

3.frame.describe():描述列的一些值:

np.random.seed(38754)
data=np.random.randint(0,15,15).reshape(5,3)
frame=DataFrame(data,index=['a','b','c','d','e'],columns=['x','y','z'])
print(frame.describe())
#輸出:
               x          y          z
count   5.000000   5.000000   5.000000 #每列非NAN數(shù)的個數(shù)
mean    6.400000  10.600000   6.200000 #每列平均值
std     4.878524   2.607681   3.768289 #標準差
min     1.000000   7.000000   0.000000
25%     3.000000  10.000000   6.000000 # 第一四分位數(shù) (Q1),又稱“較小四分位數(shù)”,等于該樣本中所有數(shù)值由小到大排列后第25%的數(shù)字。
50%     5.000000  10.000000   7.000000 #中位數(shù)
75%    11.000000  12.000000   8.000000
max    12.000000  14.000000  10.000000

4.缺失數(shù)據(jù)處理:dataframe.dropna() ,默認刪除所有存在na的行

語法:

DataFrame.dropna(axis=0, how=‘a(chǎn)ny', thresh=None, subset=None, inplace=False)

axis=0,默認對行作用,axis=1即對列作用

how=any/all:

  • any: 如果存在任何NA值,則刪除該行
  • all : 如果該行所有的值都為NA,則刪除該行
#代碼含義:對列作用,當整列都為NA值時才放棄列
np.random.seed(38754)
data=np.random.randint(0,15,15).reshape(5,3)
frame=DataFrame(data,index=['a','b','c','d','e'],columns=['x','y','z'])
#設(shè)置na值
frame.loc['a','x']=np.nan
frame.loc['b','y']=np.nan
frame.loc[0,0]=np.nan
print(frame)
print(frame.dropna(axis=1,how='all'))
#輸出:
      x     y     z   0
a   NaN  14.0   7.0 NaN
b  12.0   NaN   6.0 NaN
c   3.0   7.0   8.0 NaN
d  11.0  10.0   0.0 NaN
e   1.0  10.0  10.0 NaN
0   NaN   NaN   NaN NaN
      x     y     z
a   NaN  14.0   7.0
b  12.0   NaN   6.0
c   3.0   7.0   8.0
d  11.0  10.0   0.0
e   1.0  10.0  10.0
0   NaN   NaN   NaN

5.填充缺失值:frame.fillna()

語法:

DataFrame.fillna(value=None, method=None, axis=None, inplace=False, limit=None, downcast=None, **kwargs)

value: 變量, 字典, Series, or DataFrame

#字典填充:{‘a(chǎn)':1,‘b':2} a列填充1,b列填充2,字典填充只能按列填充
method=‘backfill', ‘bfill', ‘pad', ‘ffill', None (見實例)

limit: int 針對連續(xù)缺失值,指定填充數(shù)量

#實例
np.random.seed(38754)
data=np.random.randint(0,15,15).reshape(5,3)
frame=DataFrame(data,index=['a','b','c','d','e'],columns=['x','y','z'])
frame.loc['a','x']=np.nan
frame.loc['b','y']=np.nan
frame.loc[0,0]=np.nan
print(frame)
print(frame.fillna('new',))
print(frame.fillna('new',axis=0))
print('向前或向后填充',frame.fillna(method='ffill'))
print('對連續(xù)na值限制填充次數(shù)',frame.fillna('new',limit=3))
print('字典填充',frame.fillna(value={'x':11,'y':22,'z':33}))
#輸出
#原始frame
      x     y     z   0
a   NaN  14.0   7.0 NaN
b  12.0   NaN   6.0 NaN
c   3.0   7.0   8.0 NaN
d  11.0  10.0   0.0 NaN
e   1.0  10.0  10.0 NaN
0   NaN   NaN   NaN NaN
#用new填充na
     x    y    z    0
a  new   14    7  new
b   12  new    6  new
c    3    7    8  new
d   11   10    0  new
e    1   10   10  new
0  new  new  new  new
向前或向后填充 #用前一行(axis=0)/前一列(axis=1)的數(shù)值填充na,如果前一行或前一列也是na,則不填充
    x     y     z   0
a   NaN  14.0   7.0 NaN
b  12.0  14.0   6.0 NaN
c   3.0   7.0   8.0 NaN
d  11.0  10.0   0.0 NaN
e   1.0  10.0  10.0 NaN
0   1.0  10.0  10.0 NaN
對連續(xù)na值限制填充次數(shù)     
	 x    y    z    0
a  new   14    7  new
b   12  new    6  new
c    3    7    8  new
d   11   10    0  NaN
e    1   10   10  NaN
0  new  new  new  NaN
字典填充 #只能填充列     
	x     y     z   0
a  11.0  14.0   7.0 NaN
b  12.0  22.0   6.0 NaN
c   3.0   7.0   8.0 NaN
d  11.0  10.0   0.0 NaN
e   1.0  10.0  10.0 NaN
0  11.0  22.0  33.0 NaN

6.dataframe.head(n) :查看前n行數(shù)據(jù)(默認是前5行)

7.dataframe.tail(n) :查看后n行數(shù)據(jù)(默認是前5行)

pandas入門—匯總和計算描述統(tǒng)計

pandas對象擁有一組常用的數(shù)學和統(tǒng)計方法。它們大部分都屬于約簡和匯總統(tǒng)計,用于從Series中提取單個值(如sum或mean)或從DataFrame的行或列中提取一個Series。

跟對應的NumPy數(shù)組方法相比,它們都是基于沒有缺失數(shù)據(jù)的假設(shè)而構(gòu)建的,如

In [1]: df = pd.DataFrame([[1.4, np.nan], [7.1, -4.5],
? ?.....: ? ? ? ? ? ? ? ? ? ?[np.nan, np.nan], [0.75, -1.3]],
? ?.....: ? ? ? ? ? ? ? ? ? index=['a', 'b', 'c', 'd'],
? ?.....: ? ? ? ? ? ? ? ? ? columns=['one', 'two'])
In [2]: df
Out[2]:?
? ? one ?two
a ?1.40 ?NaN
b ?7.10 -4.5
c ? NaN ?NaN
d ?0.75 -1.3

調(diào)用DataFrame的sum方法將會返回一個含有列的和的Series

In [3]: df.sum()
Out[3]:?
one ? ?9.25
two ? -5.80

傳入axis='columns’或axis=1將會按行進行求和運算,如

In [4]: df.sum(axis=1)
Out[4]:
a ? ?1.40
b ? ?2.60
c ? ? NaN
d ? -0.55

NA值會自動被排除,除非整個切片(這里指的是行或列)都是NA。通過skipna選項可以禁用該功能:

In [5]: df.mean(axis='columns', skipna=False)
Out[5]:?
a ? ? ?NaN
b ? ?1.300
c ? ? ?NaN
d ? -0.275

有些方法(如idxmin和idxmax)返回的是間接統(tǒng)計(比如達到最小值或最大值的索引)

In [6]: df.idxmax()
Out[6]:?
one ? ?b
two ? ?d

另一些方法則是累計型的,如

In [7]: df.cumsum()
Out[7]:?
? ? one ?two
a ?1.40 ?NaN
b ?8.50 -4.5
c ? NaN ?NaN
d ?9.25 -5.8

還有一種方法,它既不是約簡型也不是累計型。describe就是一個例子,它用于一次性產(chǎn)生多個匯總統(tǒng)計

In [8]: df.describe()
Out[8]:?
? ? ? ? ? ? one ? ? ? two
count ?3.000000 ?2.000000
mean ? 3.083333 -2.900000
std ? ?3.493685 ?2.262742
min ? ?0.750000 -4.500000
25% ? ?1.075000 -3.700000
50% ? ?1.400000 -2.900000
75% ? ?4.250000 -2.100000
max ? ?7.100000 -1.300000

對于非數(shù)值型數(shù)據(jù),describe會產(chǎn)生另外一種匯總統(tǒng)計

In [9]: obj = pd.Series(['a', 'a', 'b', 'c'] * 4)
In [10]: obj.describe()
Out[10]:?
count ? ? 16
unique ? ? 3
top ? ? ? ?a
freq ? ? ? 8

相關(guān)系數(shù)與協(xié)方差

有些匯總統(tǒng)計(如相關(guān)系數(shù)和協(xié)方差)是通過參數(shù)對計算出來的

pandas-datareader包(可以用conda或pip安裝)

pip install pandas-datareader
import pandas_datareader.data as web
all_data = {ticker: web.get_data_yahoo(ticker)
? ? ? ? ? ? for ticker in ['AAPL', 'IBM', 'MSFT', 'GOOG']}
price = pd.DataFrame({ticker: data['Adj Close']
? ? ? ? ? ? ? ? ? ? ?for ticker, data in all_data.items()})
volume = pd.DataFrame({ticker: data['Volume']
? ? ? ? ? ? ? ? ? ? ? for ticker, data in all_data.items()})

計算價格的百分數(shù)變化

In [11]: returns = price.pct_change()
In [12]: returns.tail()
Out[12]:?
? ? ? ? ? ? ? ? AAPL ? ? ?GOOG ? ? ? IBM ? ? ?MSFT
Date ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
2016-10-17 -0.000680 ?0.001837 ?0.002072 -0.003483
2016-10-18 -0.000681 ?0.019616 -0.026168 ?0.007690
2016-10-19 -0.002979 ?0.007846 ?0.003583 -0.002255
2016-10-20 -0.000512 -0.005652 ?0.001719 -0.004867
2016-10-21 -0.003930 ?0.003011 -0.012474 ?0.042096

Series的corr方法用于計算兩個Series中重疊的、非NA的、按索引對齊的值的相關(guān)系數(shù)。與此類似,cov用于計算協(xié)方差

In [13]: returns['MSFT'].corr(returns['IBM'])
Out[13]: 0.49976361144151144
In [14]: returns['MSFT'].cov(returns['IBM'])
Out[14]: 8.8706554797035462e-05

另一方面,DataFrame的corr和cov方法將以DataFrame的形式分別返回完整的相關(guān)系數(shù)或協(xié)方差矩陣

In [15]: returns.corr()
Out[15]:?
? ? ? ? ? AAPL ? ? ?GOOG ? ? ? IBM ? ? ?MSFT
AAPL ?1.000000 ?0.407919 ?0.386817 ?0.389695
GOOG ?0.407919 ?1.000000 ?0.405099 ?0.465919
IBM ? 0.386817 ?0.405099 ?1.000000 ?0.499764
MSFT ?0.389695 ?0.465919 ?0.499764 ?1.000000
In [16]: returns.cov()
Out[16]:?
? ? ? ? ? AAPL ? ? ?GOOG ? ? ? IBM ? ? ?MSFT
AAPL ?0.000277 ?0.000107 ?0.000078 ?0.000095
GOOG ?0.000107 ?0.000251 ?0.000078 ?0.000108
IBM ? 0.000078 ?0.000078 ?0.000146 ?0.000089
MSFT ?0.000095 ?0.000108 ?0.000089 ?0.000215

利用DataFrame的corrwith方法,你可以計算其列或行跟另一個Series或DataFrame之間的相關(guān)系數(shù)。傳入一個Series將會返回一個相關(guān)系數(shù)值Series(針對各列進行計算)

In [17]: returns.corrwith(returns.IBM)
Out[17]:?
AAPL ? ?0.386817
GOOG ? ?0.405099
IBM ? ? 1.000000
MSFT ? ?0.499764

傳入一個DataFrame則會計算按列名配對的相關(guān)系數(shù)。這里,我計算百分比變化與成交量的相關(guān)系數(shù)

In [18]: returns.corrwith(volume)
Out[18]:?
AAPL ? -0.075565
GOOG ? -0.007067
IBM ? ?-0.204849
MSFT ? -0.092950

傳入axis='columns’即可按行進行計算。無論如何,在計算相關(guān)系數(shù)之前,所有的數(shù)據(jù)項都會按標簽對齊

唯一值、值計數(shù)以及成員資格

還有一類方法可以從一維Series的值中抽取信息,如

In [19]: obj = pd.Series(['c', 'a', 'd', 'a', 'a', 'b', 'b', 'c', 'c'])

第一個函數(shù)是unique,它可以得到Series中的唯一值數(shù)組

In [20]: uniques = obj.unique()
In [21]: uniques
Out[21]: array(['c', 'a', 'd', 'b'], dtype=object)

返回的唯一值是未排序的,如果需要的話,可以對結(jié)果再次進行排序(uniques.sort())。相似的,value_counts用于計算一個Series中各值出現(xiàn)的頻率

In [22]: obj.value_counts()
Out[22]:?
c ? ?3
a ? ?3
b ? ?2
d ? ?1

為了便于查看,結(jié)果Series是按值頻率降序排列的。value_counts還是一個頂級pandas方法,可用于任何數(shù)組或序列,如

In [23]: pd.value_counts(obj.values, sort=False)
Out[23]:?
a ? ?3
b ? ?2
c ? ?3
d ? ?1

isin用于判斷矢量化集合的成員資格,可用于過濾Series中或DataFrame列中數(shù)據(jù)的子集

In [24]: obj
Out[24]:?
0 ? ?c
1 ? ?a
2 ? ?d
3 ? ?a
4 ? ?a
5 ? ?b
6 ? ?b
7 ? ?c
8 ? ?c
In [25]: mask = obj.isin(['b', 'c'])
In [26]: mask
Out[26]:?
0 ? ? True
1 ? ?False
2 ? ?False
3 ? ?False
4 ? ?False
5 ? ? True
6 ? ? True
7 ? ? True
8 ? ? True
dtype: bool
In [27]: obj[mask]
Out[27]:?
0 ? ?c
5 ? ?b
6 ? ?b
7 ? ?c
8 ? ?c

與isin類似的是Index.get_indexer方法,它可以給你一個索引數(shù)組,從可能包含重復值的數(shù)組到另一個不同值的數(shù)組

In [28]: to_match = pd.Series(['c', 'a', 'b', 'b', 'c', 'a'])
In [29]: unique_vals = pd.Series(['c', 'b', 'a'])
In [30]: pd.Index(unique_vals).get_indexer(to_match)
Out[30]: array([0, 2, 1, 1, 0, 2])

另一個例子,如

In [31]: data
Out[31]:?
? ?Qu1 ?Qu2 ?Qu3
0 ? ?1 ? ?2 ? ?1
1 ? ?3 ? ?3 ? ?5
2 ? ?4 ? ?1 ? ?2
3 ? ?3 ? ?2 ? ?4
4 ? ?4 ? ?3 ? ?4

將pandas.value_counts傳給該DataFrame的apply函數(shù)

In [32]: result = data.apply(pd.value_counts).fillna(0)
In [33]: result
Out[33]: 
   Qu1  Qu2  Qu3
1  1.0  1.0  1.0
2  0.0  2.0  1.0
3  2.0  2.0  0.0
4  2.0  0.0  2.0
5  0.0  0.0  1.0

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • PyTorch中permute的基本用法示例

    PyTorch中permute的基本用法示例

    pytorch中的permute就像是numpy中的transpose()函數(shù)一樣,根據(jù)指定的維度進行轉(zhuǎn)置,下面這篇文章主要給大家介紹了關(guān)于PyTorch中permute的基本用法,需要的朋友可以參考下
    2022-04-04
  • python實現(xiàn)自動整理文件

    python實現(xiàn)自動整理文件

    這篇文章主要介紹了python實現(xiàn)自動整理文件,主要內(nèi)容通過整理桌面雜亂無章都是文檔和資料了解用python如何批量將不同后綴的文件移動到同一文件夾,需要的朋友可以參考一下
    2022-04-04
  • python實現(xiàn)嵌套列表平鋪的兩種方法

    python實現(xiàn)嵌套列表平鋪的兩種方法

    今天小編就為大家分享一篇python實現(xiàn)嵌套列表平鋪的兩種方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-11-11
  • Python利用wxPython制作股票價格查詢工具

    Python利用wxPython制作股票價格查詢工具

    在當今信息時代,金融市場是一個引人注目的話題。本文將介紹如何使用 Yahoo Finance API、yfinance 模塊和 wxPython 庫來創(chuàng)建一個簡單的全球股市實時價格查詢工具,希望大家能夠喜歡
    2023-05-05
  • Python 3實戰(zhàn)爬蟲之爬取京東圖書的圖片詳解

    Python 3實戰(zhàn)爬蟲之爬取京東圖書的圖片詳解

    最近在學習python3,下面這篇文章主要給大家介紹了關(guān)于Python3實戰(zhàn)爬蟲之爬取京東圖書圖片的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面來一起看看吧。
    2017-10-10
  • python如何使用split多字符分割字符串的方法

    python如何使用split多字符分割字符串的方法

    這篇文章主要給大家介紹了關(guān)于python如何使用split多字符分割字符串的相關(guān)資料,split()方法是一個非常強大的工具,可以幫助我們輕松地分割字符串,需要的朋友可以參考下
    2023-10-10
  • Python圖片縮放cv2.resize()圖文詳解

    Python圖片縮放cv2.resize()圖文詳解

    這篇文章主要給大家介紹了關(guān)于Python圖片縮放cv2.resize()的相關(guān)資料, resize是opencv庫中的一個函數(shù),主要起到對圖片進行縮放的作用,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2023-10-10
  • 使用Tensorflow?hub完成目標檢測過程詳解

    使用Tensorflow?hub完成目標檢測過程詳解

    這篇文章主要為大家介紹了使用Tensorflow?hub完成目標檢測過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-04-04
  • tensorflow獲取變量維度信息

    tensorflow獲取變量維度信息

    這篇文章主要為大家詳細介紹了tensorflow獲取變量維度信息,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-03-03
  • Python目錄下文件讀取方式

    Python目錄下文件讀取方式

    這篇文章主要介紹了Python目錄下文件讀取方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-08-08

最新評論