pandas 字符串处理

Pandas的字符串处理:

  1. 使用方法:先获取Series的str属性,然后在属性上调用函数;
  2. 只能在字符串列上使用,不能数字列上使用;
  3. Dataframe上没有str属性和处理方法
  4. Series.str并不是Python原生字符串,而是自己的一套方法,不过大部分和原生str很相似;

Series.str字符串方法列表参考文档:
https://pandas.pydata.org/pandas-docs/stable/reference/series.html#string-handling

1、获取Series的str属性,使用各种字符串处理函数

import pandas as pd
import os
from pathlib import Path
import sys 
sys.stdout = open(sys.stdout.fileno(), 'w', encoding='utf8', closefd=False)
df = pd.read_csv(os.path.join(Path(__file__).parent,'test.csv'),sep=',')
df["bWendu"].str.replace("℃", "")
print(df['bWendu'].str.isnumeric())#判断是不是数字

2、使用str的startswith、contains等得到bool的Series可以做条件查询

condition = df["ymd"].str.startswith("2018-03")
print(df[condition].head())
print(df.loc[condition,:].head())

3、需要多次str处理的链式操作

#怎样提取201803这样的数字月份?  
#1、先将日期2018-03-31替换成20180331的形式  
#2、提取月份字符串201803  
df["ymd"].str.replace("-", "").str[0:6]

4. 使用正则表达式的处理

#添加中文日期列
def get_nianyueri(x):
    year,month,day = x["ymd"].split("-")
    return f"{year}{month}{day}日"
df["中文日期"] = df.apply(get_nianyueri, axis=1)
print(df.head())
#剔除中文日期中的年月日
df["中文日期"] = df["中文日期"].str.replace('[年月日]','')
print(df.head())

你可能感兴趣的:(Pandas,pandas)