pandas學習 文字資料

2021-10-07 12:21:55 字數 3402 閱讀 3768

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[

'出生月']+

"月"+ df[

'出生日']+

"日"temp.to_frame(

).rename(columns=

)#1(b)

l_year =

list

('零一二三四五六七**'

)l_one =

[s.strip(

)for s in

list

(' 二三四五六七**')]

l_two =

[s.strip(

)for s in

list

(' 一二三四五六七**')]

df_new =

(df[

'姓名']+

':'+df[

'國籍']+

'國人,性別'

+df[

'性別']+

',生於'

+df[

'出生年'].

str.replace(r'\d'

,lambda x:l_year[

int(x.group(0)

)])+

'年'+df[

'出生月'].

(lambda x:x if

len(x)==2

else

'0'+x)\

.str.replace(r'(?p[\d])(?p\d?)'

,lambda x:l_one[

int(x.group(

'one'))

]+bool

(int

(x.group(

'one'))

)*'十'+l_two[

int(x.group(

'two'))

])+'月'

+df[

'出生日'].

(lambda x:x if

len(x)==2

else

'0'+x)\

.str.replace(r'(?p[\d])(?p\d?)'

,lambda x:l_one[

int(x.group(

'one'))

]+bool

(int

(x.group(

'one'))

)*'十'+l_two[

int(x.group(

'two'))

])+'日'

)\ .to_frame(

).rename(columns=

)1(c)

dic_year =

dic_two =

dic_one =

df_res = df_new[

'id'].

str.extract(r'(?p《姓名》[a-za-z]+):(?p《國籍》[\d])國人,性別(?p《性別》[\w]),生於(?p《出生年》[\w])年(?p《出生月》[\w]+)月(?p《出生日》[\w]+)日'

)df_res[

'出生年'

]= df_res[

'出生年'].

str.replace(r'(\w)+'

,lambda x:

''.join(

[dic_year[x.group(0)

[i]]

for i in

range(4

)]))

df_res[

'出生月'

]= df_res[

'出生月'].

str.replace(r'(?p\w?十)?(?p[\w])'

,lambda x:dic_one[x.group(

'one')]

+dic_two[x.group(

'two')]

).str.replace(r'0'

,'10'

)df_res[

'出生日'

]= df_res[

'出生日'].

str.replace(r'(?p\w?十)?(?p[\w])'

,lambda x:dic_one[x.group(

'one')]

+dic_two[x.group(

'two')]

).str.replace(r'^0'

,'10'

)df_res.equals(df)

2(a)

df1 = pd.read_csv(r'd:\python\python3.6\pysl\pre_\data\string_data_two.csv'

)df1[df1[

'col1'].

str.contains(r'[北京]|[上海]')]

2(b)

df['col2'][

~(df[

'col2'].

str.replace(r'-?\d+'

,'true')==

'true')]

#這三行有問題

df.loc[

[309

,396

,485],

'col2']=

[0,9

,7]df[

'col2'

].astype(

'int'

).mean(

)2(c)

df.columns = df.columns.

str.strip(

)df[

'col3'

].head(

)df[

'col3'][

~(df[

'col3'].

str.replace(r'-?\d+\.?\d+'

,'true')==

'true')]

df.loc[[28

,122

,332],

'col3']=

[355.3567

,9056.2253

,3534.6554

]df[

'col3'

].astype(

'float'

).mean(

)

學習pandas 讀入文字資料

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

Pandas學習之文字資料

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...

pandas文字資料

文字資料 string型別的性質 string與object的區別 字元訪問方法 string accessor methods,如str.count 會返回相應資料的nullable型別,而object會隨著缺失值的存在而改變返回型別 某些series 法不能在string上使 如 series....