Pandas學習之文字資料

2021-10-07 12:57:14 字數 2789 閱讀 7119

import numpy as np

import pandas as pd

pd.series([1

,'1'

])

0    1

1 1

dtype: object

# 上面的資料型別為 object,將其轉化為string型別

pd.series([1

,'1'])

.astype(

'str'

).astype(

'string'

)

0    1

1 1

dtype: string

s = pd.series(

['a_b_c'

,'c_d_e'

,np.nan,

'f_g_h'

],dtype=

"string"

)s

0    a_b_c

1 c_d_e

2 3 f_g_h

dtype: string

s.

str.split(

'_')

0    [a, b, c]

1 [c, d, e]

2 3 [f, g, h]

dtype: object

s.str.cat(sep=』』,na_rep = 『』)

如果沒有sep和na_rep就直接拼接,sep是分隔符引數,na_rep是替代缺失值的引數

對於單個series來說是將所有的元素合併稱為乙個字串;對多個series而言,根據索引進行合併

例子如下:

s = pd.series(

['ab'

,none

,'d'

],dtype=

'string'

)print

(s)print

('\n')s.

str.cat(

)print

(s.str

.cat())

print

('\n')s.

str.cat(sep=

',')

print

(s.str

.cat(sep=

',')

)print

('\n')s.

str.cat(sep=

',',na_rep=

'hello'

)print

(s.str

.cat(sep=

',',na_rep=

'hello'

))

0      ab

1 2 d

dtype: string

abdab,d

ab,hello,d

# s.str.repalce() 替換

s = pd.series(

['a'

,'b'

,'c'

,'aaba'

,'baca',''

,np.nan,

'caba'

,'dog'

,'cat'

],dtype=

'string'

)s

0       a

1 b

2 c

3 aaba

4 baca

5

6 7 caba

8 dog

9 cat

dtype: string

s.

str.replace(r'^[ab]'

,'***'

)

0       ***

1 ***

2 c

3 ***aba

4 ***aca

5

6 7 caba

8 dog

9 cat

dtype: string

import numpy as np

import pandas as pd

pd.series(

['10-87'

,'10-88'

,'10-89'

],dtype =

"string"

)

0    10-87

1 10-88

2 10-89

dtype: string

pd.series(

['10-87'

,'10-88'

,'10-89'

],dtype =

"string").

str.extract(

'(\d)-(\d)'

)

01

010871

1088210

89 參考:

pandas記錄之文字資料

特殊字元 資料在收集的過程中由於各種原因,彙總的資料會出現一些出乎預料的問題 資料中有特殊字元 3090 396 9 485 7 name col2,dtype string 在進行數值統計時很頭痛,一般情況下就是根據報錯資訊逐個replace df.loc df col2 str.contains...

學習pandas 讀入文字資料

import pandas as pd pd.read csv filepath or buffer 檔案路徑 不要包含中文 sep 列分隔符 header infer 指定資料中的第幾行作為變數名 names none 自定義變數名列表 index col none 將被作為索引的列,多列時只能使...

pandas學習 文字資料

1 a df pd.read csv r d python python3.6 pysl pre data string data one.csv index col 人員編號 astype str temp df 姓名 df 國籍 國人,性別 df 性別 生於 df 出生年 年 df 出生月 月 ...