pandas實用操作彙總(不斷更新)

2021-10-07 03:26:40 字數 3730 閱讀 6126

按字串包含字元篩選

按列獲取資料

讀取 .csv時選擇不同的列屬性方式:

時間格式:to_datetime

記錄下寫程式過程中用到的覺得實用的pandas操作, 不斷更新下,方便自己查詢

df[(條件1) & (條件2)]

import pandas as pd

import numpy as np

a = np.random.rand(3, 3)

b = pd.dataframe(a)

# 多重條件篩選

想在迴圈裡, 賦值不同名稱的變數時:

for i in range(5):

exec("a" + str(i) + "=i")

>>> a = 5

>>> eval('37 + a') # it is an expression

42>>> exec('37 + a') # it is an expression statement; value is ignored (none is returned)

>>> exec('a = 47') # modify a global variable as a side effect

>>> a

47>>> eval('a = 47') # you cannot evaluate a statement

traceback (most recent call last):

file "", line 1, in file "", line 1

a = 47

^syntaxerror: invalid syntax

.str.contains()

>>> b[3] = ['中國', '美國', '歐洲']

>>> b

0 1 2 3

0 0.179662 0.856873 0.291942 中國

1 0.008990 0.473773 0.659489 美國

2 0.525482 0.710721 0.241518 歐洲

>>> b[b[3].str.contains('國')]

>>> 0 1 2 3

0 0.179662 0.856873 0.291942 中國

1 0.008990 0.473773 0.659489 美國

.isin()

>>> b[b[3].isin(['中國', '美國', '英國'])]

>>> 0 1 2 3

0 0.179662 0.856873 0.291942 中國

1 0.008990 0.473773 0.659489 美國

# 通過列名獲取

tmp = df['列名'] # tmp 就是獲取的列

# 列名太長, 不打,用索引獲取第三列

tmp = df[df.columns[3]]

# 另一種方法,也可以獲取多列

tmp = df.iloc[:, 3]

tmp = df.iloc[:m 3:5]

用header引數控制:header=0或不指定時,預設第一行為columns。

pd.read_csv("1.csv", header=0)
不使用第一行, 由pandas自動生成0, 1作為columns:

pd.read_csv("1.csv", header=none)
跳過前幾行廢話:

pd.read_csv("1.csv," skip_row=3)
datetime庫是很方便的乙個管理時間的python庫,pandas與之有緊密的聯動,通過

pd.datetime()可以實現。 甚至比datetime庫本身更容易操作。

>>

>pd.to_datetime(

'20200308'

)>>

>timestamp(

'2020-03-08 00:00:00'

)>>

>>pd.to_datetime(

'2020-03-08'

)>>

>timestamp(

'2020-03-08 00:00:00'

)>>

>>

>pd.to_datetime(

'2020/03/08'

)>>

>timestamp(

'2020-03-08 00:00:00'

)

可以看到:這幾種常見的時間格式, 使用to_datetime方法都可以直接把該字串轉為datetime的時間類,極為方便,無需指定轉換格式

pandas也提供了指定轉換格式, 如:

>>

>pd.to_datetime(

'2020#03#08'

,format

='%y#%m#%d'

)>>

>timestamp(

'2020-03-08 00:00:00'

)

除了日期, 時間也類似:

>>

>pd.to_datetime(

'13:50:00'

)>>

>timestamp(

'2020-07-14 13:50:00'

)>>

>>pd.to_datetime(

'13/50/00'

,format

='%h/

%m/%s)

>>

>timestamp(

'2020-07-14 13:50:00'

)

時間和日期一起輸入也很簡單, 中間可以用空格隔開:

>>

>pd.to_datetime(

2020071213:

50:20)

>>

>timestamp(

'2020-07-12 13:50:20'

)

後面就可以用datetime的各種操作進行處理了:

>>

>

import datetime

>>

>pd.to_datetime(

2020071213:

50:20)

+ datetime.timedelta(seconds=1)

>>

>timestamp(

'2020-07-12 13:50:21'

)

實用Pandas操作記錄

from lxml import etree 檔案路徑 f e web crawler https免費http ip 第1頁https.html 生成html頁面的字串 html table text etree.tostring etree.parse f,etree.htmlparser dec...

pandas實用函式

一 統計彙總函式 import pandas as pd s pd.series s.min s.max s.sum s.mean s.count 非缺失元素的個數 s.size 所有元素的個數 s.median s.var s.std s.quantile 計算任意分位數 s.cov 計算協方差 ...

Pandas 的實用方法

1.想要刪除資料中有空數值的一行 df df.dropna print df 2.pandas讀取含有中文檔案時 df pd.read csv csv delimiter names encoding utf 8 print df 3.pandas 對index或者某一列進行全體排序 df df.s...