


Detailed explanation of 16 Pandas functions to improve your 'data cleaning' ability by 100 times!
Introduction to this article


1 data set, 16 Pandas functions
import pandas as pd df ={'姓名':[' 黄同学','黄至尊','黄老邪 ','陈大美','孙尚香'], '英文名':['Huang tong_xue','huang zhi_zun','Huang Lao_xie','Chen Da_mei','sun shang_xiang'], '性别':['男','women','men','女','男'], '身份证':['463895200003128433','429475199912122345','420934199110102311','431085200005230122','420953199509082345'], '身高':['mid:175_good','low:165_bad','low:159_bad','high:180_verygood','low:172_bad'], '家庭住址':['湖北广水','河南信阳','广西桂林','湖北孝感','广东广州'], '电话号码':['13434813546','19748672895','16728613064','14561586431','19384683910'], '收入':['1.1万','8.5千','0.9万','6.5千','2.0万']} df = pd.DataFrame(df) dfThe results are as follows:

① cat函数:用于字符串的拼接
df["姓名"].str.cat(df["家庭住址"],sep='-'*3)

② contains:判断某个字符串是否包含给定字符
df["家庭住址"].str.contains("广")

③ startswith/endswith:判断某个字符串是否以…开头/结尾
# 第一个行的“ 黄伟”是以空格开头的 df["姓名"].str.startswith("黄") df["英文名"].str.endswith("e")

④ count:计算给定字符在字符串中出现的次数
df["电话号码"].str.count("3")

⑤ get:获取指定位置的字符串
df["姓名"].str.get(-1) df["身高"].str.split(":") df["身高"].str.split(":").str.get(0)

⑥ len:计算字符串长度
df["性别"].str.len()

⑦ upper/lower:英文大小写转换
df["英文名"].str.upper() df["英文名"].str.lower()

⑧ pad+side参数/center:在字符串的左边、右边或左右两边添加给定字符
df["家庭住址"].str.pad(10,fillchar="*") # 相当于ljust() df["家庭住址"].str.pad(10,side="right",fillchar="*") # 相当于rjust() df["家庭住址"].str.center(10,fillchar="*")

⑨ repeat:重复字符串几次
df["性别"].str.repeat(3)

⑩ slice_replace:使用给定的字符串,替换指定的位置的字符
df["电话号码"].str.slice_replace(4,8,"*"*4)

⑪ replace:将指定位置的字符,替换为给定的字符串
df["身高"].str.replace(":","-")

⑫ replace:将指定位置的字符,替换为给定的字符串(接受正则表达式)
replace中传入正则表达式,才叫好用; 先不要管下面这个案例有没有用,你只需要知道,使用正则做数据清洗多好用;
df["收入"].str.replace("\d+\.\d+","正则")

⑬ split方法+expand参数:搭配join方法功能很强大
# 普通用法 df["身高"].str.split(":") # split方法,搭配expand参数 df[["身高描述","final身高"]] = df["身高"].str.split(":",expand=True) df # split方法搭配join方法 df["身高"].str.split(":").str.join("?"*5)

⑭ strip/rstrip/lstrip:去除空白符、换行符
df["姓名"].str.len() df["姓名"] = df["姓名"].str.strip() df["姓名"].str.len()

⑮ findall:利用正则表达式,去字符串中匹配,返回查找结果的列表
findall使用正则表达式,做数据清洗,真的很香!
df["身高"] df["身高"].str.findall("[a-zA-Z]+")

⑯ extract/extractall:接受正则表达式,抽取匹配的字符串(一定要加上括号)
df["身高"].str.extract("([a-zA-Z]+)") # extractall提取得到复合索引 df["身高"].str.extractall("([a-zA-Z]+)") # extract搭配expand参数 df["身高"].str.extract("([a-zA-Z]+).*?([a-zA-Z]+)",expand=True)

The above is the detailed content of Detailed explanation of 16 Pandas functions to improve your 'data cleaning' ability by 100 times!. For more information, please follow other related articles on the PHP Chinese website!

Pythonisbothcompiledandinterpreted.WhenyourunaPythonscript,itisfirstcompiledintobytecode,whichisthenexecutedbythePythonVirtualMachine(PVM).Thishybridapproachallowsforplatform-independentcodebutcanbeslowerthannativemachinecodeexecution.

Python is not strictly line-by-line execution, but is optimized and conditional execution based on the interpreter mechanism. The interpreter converts the code to bytecode, executed by the PVM, and may precompile constant expressions or optimize loops. Understanding these mechanisms helps optimize code and improve efficiency.

There are many methods to connect two lists in Python: 1. Use operators, which are simple but inefficient in large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use the = operator, which is both efficient and readable; 4. Use itertools.chain function, which is memory efficient but requires additional import; 5. Use list parsing, which is elegant but may be too complex. The selection method should be based on the code context and requirements.

There are many ways to merge Python lists: 1. Use operators, which are simple but not memory efficient for large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use itertools.chain, which is suitable for large data sets; 4. Use * operator, merge small to medium-sized lists in one line of code; 5. Use numpy.concatenate, which is suitable for large data sets and scenarios with high performance requirements; 6. Use append method, which is suitable for small lists but is inefficient. When selecting a method, you need to consider the list size and application scenarios.

Compiledlanguagesofferspeedandsecurity,whileinterpretedlanguagesprovideeaseofuseandportability.1)CompiledlanguageslikeC arefasterandsecurebuthavelongerdevelopmentcyclesandplatformdependency.2)InterpretedlanguageslikePythonareeasiertouseandmoreportab

In Python, a for loop is used to traverse iterable objects, and a while loop is used to perform operations repeatedly when the condition is satisfied. 1) For loop example: traverse the list and print the elements. 2) While loop example: guess the number game until you guess it right. Mastering cycle principles and optimization techniques can improve code efficiency and reliability.

To concatenate a list into a string, using the join() method in Python is the best choice. 1) Use the join() method to concatenate the list elements into a string, such as ''.join(my_list). 2) For a list containing numbers, convert map(str, numbers) into a string before concatenating. 3) You can use generator expressions for complex formatting, such as ','.join(f'({fruit})'forfruitinfruits). 4) When processing mixed data types, use map(str, mixed_list) to ensure that all elements can be converted into strings. 5) For large lists, use ''.join(large_li

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version
SublimeText3 Linux latest version

Zend Studio 13.0.1
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
