最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python中pandas常用命令詳解

 更新時(shí)間:2022年07月25日 11:48:35   作者:坐望云起  
pandas 是基于NumPy 的一種工具,該工具是為了解決數(shù)據(jù)分析任務(wù)而創(chuàng)建的,這篇文章主要介紹了python中pandas常用命令,需要的朋友可以參考下

pandas 是基于NumPy 的一種工具,該工具是為了解決數(shù)據(jù)分析任務(wù)而創(chuàng)建的。Pandas 納入了大量庫和一些標(biāo)準(zhǔn)的數(shù)據(jù)模型,提供了高效地操作大型數(shù)據(jù)集所需的工具。pandas提供了大量能使我們快速便捷地處理數(shù)據(jù)的函數(shù)和方法。你很快就會(huì)發(fā)現(xiàn),它是使Python成為強(qiáng)大而高效的數(shù)據(jù)分析環(huán)境的重要因素之一。

1、pandas

pandas 是一個(gè)多功能且功能強(qiáng)大的數(shù)據(jù)科學(xué)庫。 

2、讀取數(shù)據(jù)

pd.read_csv("data.csv")

3、讀取指定列

pd.read_csv("data.csv", usecols=["date", "price"])

4、讀取并解析日期

pd.read_csv("data.csv", parse_dates=["date"])

5、讀取時(shí)指定數(shù)據(jù)類型

        在讀取時(shí)設(shè)置類別數(shù)據(jù)類型可以節(jié)省內(nèi)存。

pd.read_csv("data.csv", dtype={"house_type": "category"})

6、讀取時(shí)設(shè)置索引

pd.read_csv("data.csv", index_col="date")

7、設(shè)置讀取的行數(shù)

pd.read_csv("data.csv", nrows=100)

8、讀取時(shí)跳過行數(shù)

pd.read_csv("data.csv", skiprows=[1, 5])  # skips line 1 and 5
pd.read_csv("data.csv", skiprows=100)  # skips the first 100 lines
pd.read_csv("data.csv", skiprows=lambda x: x > 0 and np.random.rand() > 0.1) # skip 90% of the rows

9、指定NA值

pd.read_csv("data.csv", na_values=["?"])

10、設(shè)置布爾值

pd.read_csv("data.csv", true_values=["yes"], false_values=["no"])

11、一次讀取多個(gè)文件后合并

import glob
import os
files = glob.glob("file_*.csv")
result = pd.concat([pd.read_csv(f) for f in files], ignore_index=True)

12、復(fù)制數(shù)據(jù)

df = pd.read_clipboard() 

13、從 PDF 文件中讀取表格

from tabula import read_pdf
# Read pdf into list of DataFrame
df = read_pdf('test.pdf', pages='all')

14、快速可視化數(shù)據(jù)集

import pandas_profiling
df = pd.read_csv("data.csv")
profile = df.profile_report(title="Pandas Profiling Report")
profile.to_file(output_file="output.html")

15、按dtype過濾列

# 選擇
df.select_dtypes(include="number")
df.select_dtypes(include=["category", "datetime"])
 
# 排除
df.select_dtypes(exclude="object")

16、推斷數(shù)據(jù)類型

df.infer_objects().dtypes

17、向下轉(zhuǎn)換數(shù)值類型

pd.to_numeric(df.numeric_col, downcast="integer") # smallest signed int dtype
pd.to_numeric(df.numeric_col, downcast="float")  # smallest float dtype

18、防止錯(cuò)誤值并填充

# apply to whole data frame
df = df.apply(pd.to_numeric, errors="coerce")
# apply to specific columns
pd.to_numeric(df.numeric_column, errors="coerce")
# filling NA values with zero
pd.to_numeric(df.numeric_column, errors="coerce").fillna(0)

19、按列數(shù)據(jù)類型轉(zhuǎn)換

df = df.astype(
    {
        "date": "datetime64[ns]",
        "price": "int",
        "is_weekend": "bool",
        "status": "category",
    }
)

20、重命名列

df = df.rename({"PRICE": "price", "Date (mm/dd/yyyy)": "date"}, axis=1)

21、添加后綴和前綴

df.add_prefix("pre_")
df.add_suffix("_suf")

22、從原列創(chuàng)建新列

# create new column of Fahrenheit values from Celcius
df.assign(temp_f=lambda x: x.temp_c * 9 / 5 + 32)

23、在特定位置插入列

random_col = np.random.randint(10, size=len(df))
df.insert(3, 'random_col', random_col) # inserts at third column

24、三元表達(dá)式

df["logic"] = np.where(df["price"] > 5, "high", "low")

25、刪除列

df.drop('col1', axis=1, inplace=True)
df = df.drop(['col1','col2'], axis=1)
s = df.pop('col')
del df['col']
df.drop(df.columns[0], inplace=True)

26、修改列名

df.columns = df.columns.str.lower()
df.columns = df.columns.str.replace(' ', '_')

27、判斷包含

df['name'].str.contains("John")
df['phone_num'].str.contains('...-...-....', regex=True)  # regex
df['email'].str.contains('gmail')

28、根據(jù)正則查找

pattern = '([A-Z0-9._%+-]+)@([A-Z0-9.-]+)\\.([A-Z]{2,4})'
df['email'].str.findall(pattern, flags=re.IGNORECASE)

29、檢查缺失值并打印缺失百分比

def missing_vals(df):
    """prints out columns with perc of missing values"""
    missing = [
        (df.columns[idx], perc)
        for idx, perc in enumerate(df.isna().mean() * 100)
        if perc > 0
    ]
 
    if len(missing) == 0:
        return "no missing values"
    
    # sort desc by perc
    missing.sort(key=lambda x: x[1], reverse=True)
 
    print(f"There are a total of {len(missing)} variables with missing values\n")
 
    for tup in missing:
        print(str.ljust(f"{tup[0]:<20} => {round(tup[1], 3)}%", 1))
missing_vals(df)

30、處理缺失值

# drop 
df.dropna(axis=0)
df.dropna(axis=1)
# impute
df.fillna(0)
df.fillna(method="ffill")
df.fillna(method='bfill')
# replace
df.replace( -999, np.nan)
df.replace("?", np.nan)
# interpolate
ts.interpolate() # time series
df.interpolate() # fill all consecutive values forward
df.interpolate(limit=1) # fill one consecutive value forward
df.interpolate(limit=1, limit_direction="backward")
df.interpolate(limit_direction="both")

31、從今天/之前獲取 X 小時(shí)/天/周

# from today
date.today() + datetime.timedelta(hours=30)
date.today() + datetime.timedelta(days=30)
date.today() + datetime.timedelta(weeks=30)
 
# ago
date.today() - datetime.timedelta(days=365)

32、過濾兩個(gè)日期

df[(df["Date"] > "2015-01-01") & (df["Date"] < "2017-01-01")]

33、按日/月/年過濾

df[(df["Date"] > "2015-01-01") & (df["Date"] < "2017-01-01")]

34、格式化數(shù)據(jù)格式

format_dict = {
    "Date": "{:%d/%m/%y}",
    "Open": "${:.2f}",
    "Close": "${:.2f}",
    "Volume": "{:,}",
}
 
df.style.format(format_dict)

35、設(shè)置數(shù)據(jù)顏色

(
    df.style.format(format_dict)
    .hide_index()
    .highlight_min(["Open"], color="red")
    .highlight_max(["Open"], color="green")
    .background_gradient(subset="Close", cmap="Greens")
    .bar('Volume', color='lightblue', align='zero')
    .set_caption('Tesla Stock Prices in 2017')
)

36、獲取一列中最大最小項(xiàng)的id

df['col'].idxmin()
df['col'].idxmax()

37、對(duì)數(shù)據(jù)列應(yīng)用函數(shù)

df.applymap(lambda x: np.log(x))

38、隨機(jī)打亂數(shù)據(jù)

df.sample(frac=1, random_state=7).reset_index(drop=True)

39、時(shí)間序列的百分比變化

df['col_name'].pct_change()

40、分配等級(jí)

df['rank'] = df['column_to_rank'].rank()

41、檢查內(nèi)存占用

df.memory_usage().sum() / (1024**2) #converting to MB

42、將列的值分解為多行

df.explode("col_name").reset_index(drop=True)

43、將數(shù)量較小的類別轉(zhuǎn)換為“其他”

subclass = df.MSSubClass
subclass.value_counts()
top_five = subclass.value_counts().nlargest(5).index
mssubclass_new = subclass.where(subclass.isin(top_five), other="Other")
mssubclass_new.value_counts()

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

相關(guān)文章

  • Python 字符串轉(zhuǎn)換為整形和浮點(diǎn)類型的方法

    Python 字符串轉(zhuǎn)換為整形和浮點(diǎn)類型的方法

    今天小編就為大家分享一篇Python 字符串轉(zhuǎn)換為整形和浮點(diǎn)類型的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-07-07
  • python實(shí)現(xiàn)多圖像疊置輸出

    python實(shí)現(xiàn)多圖像疊置輸出

    這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)多圖像疊置輸出,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-04-04
  • 調(diào)整Jupyter notebook的啟動(dòng)目錄操作

    調(diào)整Jupyter notebook的啟動(dòng)目錄操作

    這篇文章主要介紹了調(diào)整Jupyter notebook的啟動(dòng)目錄操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-04-04
  • Python中JsonPath提取器和正則提取器

    Python中JsonPath提取器和正則提取器

    本文主要介紹了Python中JsonPath提取器和正則提取器,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-03-03
  • 解決ImportError:DLL load failed while importing win32api:找不到指定的模塊

    解決ImportError:DLL load failed while impo

    在安裝pywin32后,可能會(huì)出現(xiàn)無法導(dǎo)入win32api的錯(cuò)誤,一個(gè)有效的解決方案是運(yùn)行pywin32_postinstall.py腳本,首先,打開cmd并切換到環(huán)境的Scripts文件夾,確保存在pywin32_postinstall.py文件
    2024-09-09
  • mac PyCharm添加Python解釋器及添加package路徑的方法

    mac PyCharm添加Python解釋器及添加package路徑的方法

    今天小編就為大家分享一篇mac PyCharm添加Python解釋器及添加package路徑的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-10-10
  • python多進(jìn)程 主進(jìn)程和子進(jìn)程間共享和不共享全局變量實(shí)例

    python多進(jìn)程 主進(jìn)程和子進(jìn)程間共享和不共享全局變量實(shí)例

    這篇文章主要介紹了python多進(jìn)程 主進(jìn)程和子進(jìn)程間共享和不共享全局變量實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-04-04
  • Python數(shù)據(jù)可視化常用4大繪圖庫原理詳解

    Python數(shù)據(jù)可視化常用4大繪圖庫原理詳解

    這篇文章主要介紹了Python數(shù)據(jù)可視化常用4大繪圖庫原理詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-10-10
  • Tensorflow 查看變量的值方法

    Tensorflow 查看變量的值方法

    今天小編就為大家分享一篇Tensorflow 查看變量的值方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-06-06
  • 如何利用python將Xmind用例轉(zhuǎn)為Excel用例

    如何利用python將Xmind用例轉(zhuǎn)為Excel用例

    這篇文章主要介紹了如何利用python將Xmind用例轉(zhuǎn)為Excel用例,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下
    2022-06-06

最新評(píng)論

抚远县| 漳平市| 峡江县| 临夏市| 理塘县| 灌南县| 合川市| 广河县| 潞城市| 抚顺县| 建德市| 寻乌县| 上栗县| 大丰市| 突泉县| 明溪县| 抚顺市| 武川县| 获嘉县| 黄浦区| 罗山县| 读书| 三河市| 榆社县| 松桃| 阳原县| 景洪市| 都兰县| 平阴县| 临汾市| 白玉县| 亳州市| 定兴县| 屯昌县| 额尔古纳市| 甘洛县| 长垣县| 牙克石市| 博乐市| 陆川县| 浏阳市|