Python Pandas庫與資料處理

2021-10-02 06:53:21 字數 1568 閱讀 3635

讀取資料

import pandas as pd

pd.read_csv(" ")

觀察資料

print(***.dtypes) #每列的資料型別

print(***.head(n)) #前n行資料

print(***.tail(n)) #後n行資料

print(***.columns) #每一列的名字

print(***.shape) #行列數

print(***.loc[0]) #索引為0的(第乙個)資料

print(***[列1, 列2]) #輸出指定列

***[新列名] = 變數 #將陣列加入資料框

***.max()

***.mean()

new = ***.sort_values("列", inplace = true, ascending = true) #按照指定列排序,生成新的資料框,公升序

new.reset_index(drop = true) #排序後生成新的索引,並且刪去原有索引

pd.to_datetime() #轉換格式

缺失值

isnull = pd.isnull(dataframe[array]) #判斷列中元素是否為空

dataframe[isnull] #提取na值所在的行

dataframe[isnull = false] #提取非na值

len(isnull) #缺失值數目

***.dropna(axis = 1, subset = (列1, 列2)) #刪除帶有缺失值的列,只對列1,2進行缺失值篩選操作

篩選以特定字串開頭/結尾的變數

colnames = ***.columns.tolist() #將列名變為list格式

new = #預分配

for i in colnames

if i endswith('文字') #endswith or startswith

資料透視表

***.pivot_table(index = '', values = '', aggfunc = np.mean)

#index 按照什麼分組(男女、年級等)

#values 對什麼進行統計(分數、年齡等等)

#aggfunc 統計方式(均值、極值)

自定義函式

#第一種方式

def 函式名(輸入變數)

。。。。。。

return 變數或'字串'

#第二種方式

f = lambda x:pow(x, 2) #lambda定義匿名函式,輸入變數為x,輸出x的平方

read_csv之後得到的是dataframe,dataframe的每一行或列是乙個series。如果想自建series,需要

from pandas import series

*** = series(變數, index = )

Python pandas連線mysql資料庫

首先安裝包 pip install pandas pip install sqlalchemy pip install pymysql 初始化資料庫連線 import pandas as pd from sqlalchemy import create engine 初始化資料庫連線 按實際情況依次...

Python Pandas庫處理excel表

讀取 儲存excel表 data pandas.read excel filepath data.to excel filepath,index none index none表示不將dataframe的行索引存入excel讀取dataframe某行 列 讀取data中行索引為5 6,列索引為1 3...

python pandas庫具體用法

一 學習資料探勘,如果是用python的話,必須掌握好科學計算的相關庫,我先學習了pandas的一些具體操作 encoding utf 8 import numpy as np import os import pylab as pl import pandas as pd from pandas ...