pandas 常用文字操作函式

2021-10-22 09:26:53 字數 2584 閱讀 8008

# # 第二課 pandas文字資料分析

# ## 第五節 常用的文字資料操作函式小結

# in[1]:

import pandas as pd

import numpy as np

# in[2]:

data_df = pd.read_csv(

)data_df.head(

)# * strip() 從兩側的series/index中的每個字串中刪除空格(包括換行符)。

# in[3]:

s = pd.series(

['1. ant. '

,'2. bee!\n'

,'3. cat?\t'

, np.nan])s

# in[4]:

s.str

.len()

# in[5]:

s.str

.strip(

)# in[6]:

s.str

.strip().

str.

len(

)# * str.contains() 如果元素中包含子字串,則返回每個元素的布林值true,否則為false。

# in[7]:

# 區分大小寫

data_df[

'region'].

str.contains(

'europe'

).head(10)

# in[8]:

# 忽視大小寫

data_df[

'region'].

str.contains(

'europe'

, case=

false

).head(10)

# in[9]:

# 資料過濾

data_df[data_df[

'region'].

str.contains(

'europe'

, case=

false)]

# * str.repeat() 重複每個元素指定的次數。

# in[10]:

s = pd.series(

['a'

,'b'

,'c'])

s# in[11]:

# 每個資料重複相同次數

s.str

.repeat(repeats=2)

# in[12]:

# 每個資料重複不同的次數

s.str

.repeat(repeats=[1

,2,3

])# * str.startswith() 如果series/index中的元素以模式開始,則返回true。

# in[13]:

# 找出以z開頭的國家記錄

data_df[data_df[

'country'].

str.startswith(

'z')

]# * str.endswith() 如果series/index中的元素以模式結束,則返回true。

# in[14]:

# 找出以y結尾的國家記錄

data_df[data_df[

'country'].

str.endswith(

'y')

]# * str.swapcase() 變換字母大小寫

# in[15]:

data_df[

'country'].

str.swapcase(

).head(

)# * str.islower() 檢查series/index中每個字串中的所有字元是否小寫,返回布林值

# * str.isupper() 檢查series/index中每個字串中的所有字元是否大寫,返回布林值

# * str.isnumeric() 檢查series/index中每個字串中的所有字元是否為數字,返回布林值。

# in[16]:

data_df2 = pd.dataframe(

)data_df2[

'col1']=

['abc'

,'abc'

,'abc'

]data_df2[

'col2']=

['1212.123'

,'abc'

,'2323'

]data_df2

# in[17]:

data_df2[

'col1'].

str.islower(

)# in[18]:

data_df2[

'col1'].

str.isupper(

)# in[19]:

# 注意檢查的是字串中的每個字元

data_df2[

'col2'].

str.isnumeric(

)# in[ ]:

Pandas 常用操作

按某一列的值排序 對某一列去重 刪除某一列 重新命名列名 顯示每一列的名稱 篩選出某幾列 重置索引 設定索引 檢測dataframe是否為空 df date df.sort values by looked up at ascending false df date drop df date.dro...

pandas 常用函式

本文翻譯自文章 pandas cheat sheet python for data science 同時新增了部分註解。對於資料科學家,無論是資料分析還是資料探勘來說,pandas是乙個非常重要的python包。它不僅提供了很多方法,使得資料處理非常簡單,同時在資料處理速度上也做了很多優化,使得和...

Pandas常用函式

count 非 na 值的數量 describe 針對 series 或 df 的列計算匯 計 min max 最小值和最大值 argmin argmax 最小值和最大值的索引位置 整數 idxmin idxmax 最小值和最大值的索引值 quantile 樣本分位數 0 到 1 sum求和 mea...