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

Python中的Pandas庫操作小結(jié)

 更新時(shí)間:2023年06月07日 14:19:52   作者:天佑  
Pandas 是一個(gè)用于數(shù)據(jù)分析的 Python 第三方庫,能夠處理和分析不同格式的數(shù)據(jù),Pandas 提供了兩種數(shù)據(jù)結(jié)構(gòu),分別為 Series 和 DataFrame,靈活而方便地進(jìn)行數(shù)據(jù)分析和操作,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧

Pandas庫介紹

Pandas 是一個(gè)用于數(shù)據(jù)分析的 Python 第三方庫,能夠處理和分析不同格式的數(shù)據(jù),例如:CSV、Excel、SQL 數(shù)據(jù)庫等。Pandas 提供了兩種數(shù)據(jù)結(jié)構(gòu),分別為 Series 和 DataFrame,靈活而方便地進(jìn)行數(shù)據(jù)分析和操作。

以下是 Pandas 的核心概念和功能:

  • Series:類似于 NumPy 的 ndarray,可以存儲(chǔ)一維數(shù)組,不同的是它能夠自定義索引值。
  • DataFrame:是一個(gè)表格型的數(shù)據(jù)結(jié)構(gòu),擁有行和列的索引,類似于 Excel 表格,可以存儲(chǔ)多維數(shù)組。DataFrame 可以被看成是Series類型的容器,每一列都是一個(gè)Series。
  • Pandas 讀取和寫入數(shù)據(jù):Pandas 可以處理不同文件格式和數(shù)據(jù)源的數(shù)據(jù),例如:CSV、Excel、SQL 數(shù)據(jù)庫等。使用 Pandas,你可以輕松的讀取、整理和清理這些數(shù)據(jù),最終生成一個(gè) DataFrame。
  • 數(shù)據(jù)清洗:Pandas 可以構(gòu)建數(shù)據(jù)管道,以圖形化的方式進(jìn)行數(shù)據(jù)操作和轉(zhuǎn)換,例如:刪減列和行,數(shù)據(jù)的修改和替換,數(shù)據(jù)去重等。
  • 數(shù)據(jù)可視化:Pandas 可以通過 matplotlib 庫進(jìn)行數(shù)據(jù)可視化,將最終的數(shù)據(jù)可視化并呈現(xiàn)給用戶。

Pandas 的功能十分豐富,可以處理任何類型的數(shù)據(jù)和數(shù)據(jù)結(jié)構(gòu),并提供多種方式進(jìn)行數(shù)據(jù)操作和分析。由于其易學(xué)易用和高效性,Pandas 已成為數(shù)據(jù)科學(xué)和數(shù)據(jù)分析領(lǐng)域必不可少的工具之一。

如何從CSV、Excel、JSON等不同文件格式中讀取數(shù)據(jù)到Pandas中?

Pandas 支持讀取和寫入多種數(shù)據(jù)文件格式,包括 CSV、Excel、JSON 等。下面是一些示例代碼,演示如何將不同的文件格式讀取到 Pandas 中。

從 CSV 文件中讀取數(shù)據(jù):

import pandas as pd data = pd.read_csv('data.csv') print(data)

從 Excel 文件中讀取數(shù)據(jù):

import pandas as pd data = pd.read_excel('data.xlsx', sheet_name='Sheet1') print(data)

從 JSON 文件中讀取數(shù)據(jù):

import pandas as pd data = pd.read_json('data.json') print(data)

你還可以設(shè)置讀取時(shí)的參數(shù),例如解析數(shù)據(jù)的方式、數(shù)據(jù)類型等。在 Pandas 中,有許多參數(shù)可以配置,以適應(yīng)不同的需求和數(shù)據(jù)類型。可以參考官方文檔以了解更多信息。

如何在Pandas中處理缺失值(NaN)?

Pandas中處理缺失值有以下幾種方法:

  • dropna()函數(shù):刪除包含NaN的行或列(默認(rèn)刪除包含NaN的行)。
  • fillna()函數(shù):將NaN值替換為其他數(shù)據(jù)(可以是0,平均值等)。
  • isna()函數(shù):返回一個(gè)布爾值,表示數(shù)據(jù)是否為NaN。
  • notna()函數(shù):返回一個(gè)布爾值,表示數(shù)據(jù)是否不為NaN。
  • replace()函數(shù):替換數(shù)據(jù)中的一個(gè)值為另一個(gè)值。

下面是一個(gè)示例代碼,演示如何使用Pandas處理缺失值:

import pandas as pd
import numpy as np
# 創(chuàng)建包含NaN的DataFrame
data = {'A': [1, 2, np.nan, 4],
        'B': [5, np.nan, np.nan, 8],
        'C': [9, 10, 11, 12]}
df = pd.DataFrame(data)
# 使用dropna刪除包含NaN的行
df1 = df.dropna()
print(df1)
# 使用fillna將NaN替換為0
df2 = df.fillna(0)
print(df2)
# 使用fillna將NaN替換為平均值
df3 = df.fillna(df.mean())
print(df3)
# 使用isna返回布爾值
df4 = df.isna()
print(df4)
# 使用replace替換值
df5 = df.replace(np.nan, 0)
print(df5)

輸出結(jié)果

     A    B   C
0  1.0  5.0   9
3  4.0  8.0  12

     A    B   C
0  1.0  5.0   9
1  2.0  0.0  10
2  0.0  0.0  11
3  4.0  8.0  12

     A    B   C
0  1.0  5.0   9
1  2.0  6.5  10
2  2.333333  6.5  11
3  4.0  8.0  12

       A      B      C
0  False  False  False
1  False   True  False
2   True   True  False
3  False  False  False

     A    B   C
0  1.0  5.0   9
1  2.0  0.0  10
2  0.0  0.0  11
3  4.0  8.0  12

如何對(duì)Pandas中的數(shù)據(jù)進(jìn)行簡(jiǎn)單的描述性統(tǒng)計(jì)?

Pandas中可以使用describe方法對(duì)數(shù)據(jù)進(jìn)行簡(jiǎn)單的描述性統(tǒng)計(jì),包括計(jì)數(shù)、平均數(shù)、標(biāo)準(zhǔn)差、最小值、25%,50%和75%分位數(shù)以及最大值等。具體實(shí)現(xiàn)步驟如下:

  • 導(dǎo)入Pandas庫。
  • 讀取數(shù)據(jù)。
  • 使用describe方法對(duì)數(shù)據(jù)進(jìn)行簡(jiǎn)單的描述性統(tǒng)計(jì)。
import pandas as pd
# 讀取csv文件
data = pd.read_csv('data.csv')
# 對(duì)整個(gè)數(shù)據(jù)框進(jìn)行描述性統(tǒng)計(jì)
data.describe()
# 對(duì)特定列進(jìn)行描述性統(tǒng)計(jì)(例如,統(tǒng)計(jì)age列的描述性統(tǒng)計(jì))
data['age'].describe()

如何對(duì)Pandas中的數(shù)據(jù)進(jìn)行分組與聚合操作?

Pandas中的數(shù)據(jù)分組和聚合操作可以通過groupby方法來實(shí)現(xiàn)。具體步驟如下:

  • 使用groupby方法將數(shù)據(jù)按照某一列或多列進(jìn)行分組,例如:df.groupby('列名'),或者df.groupby(['列名1', '列名2'])
  • 對(duì)分組后的數(shù)據(jù)進(jìn)行聚合計(jì)算,可以使用sum、mean、count等方法,例如:df.groupby('列名').sum() 或 df.groupby(['列名1', '列名2']).mean()
  • 可以使用agg方法進(jìn)行自定義聚合計(jì)算,例如:df.groupby('列名').agg({'列名1': 'sum', '列名2': 'mean'})
  • 也可以使用apply方法對(duì)每個(gè)分組執(zhí)行特定的函數(shù),例如:df.groupby('列名').apply(function)
  • 可以使用transform方法對(duì)每個(gè)分組進(jìn)行數(shù)據(jù)轉(zhuǎn)換,例如:df.groupby('列名').transform(lambda x: x - x.mean())

總之,Pandas的數(shù)據(jù)分組和聚合操作非常靈活,可以根據(jù)不同的需求進(jìn)行不同的操作,提供了很大的便利性。

如何使用Pandas進(jìn)行日期和時(shí)間處理?

Pandas支持datetime格式的數(shù)據(jù),可以使用pandas.to_datetime函數(shù)將字符串格式的日期轉(zhuǎn)換為datetime格式,并進(jìn)行各類日期和時(shí)間的計(jì)算和操作。

以下是一些常用的日期和時(shí)間處理方法:

  • 創(chuàng)建日期時(shí)間索引 可以使用pandas.date_range()和pandas.DatetimeIndex()函數(shù)創(chuàng)建日期時(shí)間索引。
  • 轉(zhuǎn)換日期格式 可以使用pandas.to_datetime()函數(shù)將字符串格式的日期轉(zhuǎn)換為datetime格式,或?qū)⑷掌诟袷交癁橹付ǜ袷健?/li>
  • 獲取日期時(shí)間屬性 可以使用.dt屬性來獲取datetime格式數(shù)據(jù)的年、月、日、小時(shí)、分鐘、秒等屬性值。
  • 偏移量計(jì)算 可以使用pandas.DateOffset()函數(shù)來進(jìn)行日期偏移量計(jì)算,如計(jì)算前一天、前一周、前一月等。
  • 時(shí)間序列重采樣 可以使用pandas.resample()函數(shù)對(duì)時(shí)間序列數(shù)據(jù)進(jìn)行重采樣,如按月、周、日等頻率進(jìn)行統(tǒng)計(jì)。
  • 日期時(shí)間操作 可以使用datetime.timedelta()函數(shù)進(jìn)行日期和時(shí)間的加減操作。
import pandas as pd
import datetime
# 創(chuàng)建日期時(shí)間索引
dates = pd.date_range(start='20220101', end='20220110', freq='D')
print(dates)
# 轉(zhuǎn)換日期格式
date_str = '20220101'
date_obj = pd.to_datetime(date_str, format='%Y-%m-%d')
print(date_obj)
# 獲取日期時(shí)間屬性
print(date_obj.year)
print(date_obj.month)
print(date_obj.day)
print(date_obj.hour)
print(date_obj.minute)
print(date_obj.second)
# 偏移量計(jì)算
date_offset = pd.DateOffset(months=1)
new_date = date_obj + date_offset
print(new_date)
# 時(shí)間序列重采樣
data = pd.DataFrame({'date': dates, 'value': range(len(dates))})
data.set_index('date', inplace=True)
resample_data = data.resample('W').sum()
print(resample_data)
# 日期時(shí)間操作
delta = datetime.timedelta(days=30)
new_date = date_obj + delta
print(new_date)

如何在Pandas中進(jìn)行數(shù)據(jù)的透視和堆疊操作?

Pandas中可以通過pivot_table()函數(shù)進(jìn)行數(shù)據(jù)透視,也可以通過stack()函數(shù)進(jìn)行數(shù)據(jù)堆疊。下面是示例代碼:

import pandas as pd
# 創(chuàng)建數(shù)據(jù)集
df = pd.DataFrame({
   'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
   'B': ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
   'C': [1, 2, 3, 4, 5, 6, 7, 8],
   'D': [10, 20, 30, 40, 50, 60, 70, 80]
})
# 進(jìn)行數(shù)據(jù)透視
result = df.pivot_table(values='D', index=['A', 'B'], columns=['C'])
print(result)
C          1     2     3     4     5     6     7     8
A   B                                                
bar one   20.0   NaN   NaN   NaN   NaN  60.0   NaN   NaN
    three  NaN   NaN   NaN  40.0   NaN   NaN   NaN   NaN
    two    NaN  20.0   NaN   NaN   NaN  60.0   NaN   NaN
foo one   10.0   NaN   7.0   NaN   NaN   NaN  70.0   NaN
    three  NaN   NaN   NaN   NaN   NaN   NaN   NaN  80.0
    two   50.0  30.0   NaN   NaN  50.0   NaN   NaN   NaN
import pandas as pd
# 創(chuàng)建數(shù)據(jù)集
df = pd.DataFrame({
   'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
   'B': ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
   'C': [1, 2, 3, 4, 5, 6, 7, 8],
   'D': [10, 20, 30, 40, 50, 60, 70, 80]
})
# 進(jìn)行數(shù)據(jù)堆疊
stacked = df.stack()
print(stacked)
0  A      foo
   B      one
   C        1
   D       10
1  A      bar
         ... 
6  C        7
   D       70
7  A      foo
   B    three
   C        8
   D       80

如何在Pandas中進(jìn)行數(shù)據(jù)的可視化?

Pandas提供了多種數(shù)據(jù)可視化方法,其中常用的是基于Matplotlib的可視化。以下是在Pandas中進(jìn)行數(shù)據(jù)可視化的步驟:

  • 導(dǎo)入Pandas和Matplotlib庫:
  • 讀取數(shù)據(jù)并創(chuàng)建DataFrame對(duì)象:
  • 數(shù)據(jù)進(jìn)行必要的處理和清洗:
  • 用DataFrame.plot()方法進(jìn)行可視化:
import pandas as pd
import matplotlib.pyplot as plt
# 讀取數(shù)據(jù)
data = pd.read_csv('data.csv')
df = pd.DataFrame(data)
# 清洗數(shù)據(jù)
df = df.dropna()
# 繪制柱狀圖
df.plot(kind='bar', x='country', y='population')
plt.title('Population by Country')
plt.xlabel('Country')
plt.ylabel('Population')
plt.show()
# 繪制散點(diǎn)圖
df.plot(kind='scatter', x='gdp_per_capita', y='life_expectancy')
plt.title('Relationship between GDP per capita and life expectancy') 
plt.xlabel('GDP per capita')
plt.ylabel('Life expectancy')
plt.show()

如何在Pandas中進(jìn)行數(shù)據(jù)的篩選和排序?

在Pandas中,可以使用以下的方式對(duì)數(shù)據(jù)進(jìn)行篩選和排序:

  • 使用布爾索引進(jìn)行數(shù)據(jù)篩選:可以通過指定列的條件來篩選符合條件的數(shù)據(jù)。例如,df[df['age'] >= 18]可以選出所有年齡大于等于 18 的數(shù)據(jù)。
  • 使用 isin() 函數(shù)進(jìn)行數(shù)據(jù)篩選:可以使用 isin() 函數(shù)來篩選符合條件的數(shù)據(jù)。例如,df[df['city'].isin(['Shanghai', 'Beijing'])]可以篩選出居住在上海和北京的數(shù)據(jù)。
  • 使用 sort_values() 函數(shù)進(jìn)行數(shù)據(jù)排序:可以使用 sort_values() 函數(shù)對(duì)數(shù)據(jù)進(jìn)行排序。例如,df.sort_values(by=['age', 'salary'], ascending=[False, True])可以按照年齡降序、薪水升序的方式進(jìn)行排序。
  • 使用 nlargest() 和 nsmallest() 函數(shù)進(jìn)行數(shù)據(jù)篩選:可以使用 nlargest() 和 nsmallest() 函數(shù)來篩選前n個(gè)或后n個(gè)最大值或最小值。例如,df.nlargest(10, 'salary')可以選出薪水前10名的員工數(shù)據(jù)。

到此這篇關(guān)于Python中的Pandas庫的文章就介紹到這了,更多相關(guān)Python Pandas庫內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論