Table of Contents
Import data" >Import data
Export data" >Export data
View data" >View data
Data selection" >Data selection
数据处理" >数据处理
数据分组、排序、透 视" >数据分组、排序、透 视
数据合并" >数据合并
Home Backend Development Python Tutorial Summarized these 67 pandas functions, which perfectly solve data processing and are ready to use!

Summarized these 67 pandas functions, which perfectly solve data processing and are ready to use!

Aug 10, 2023 pm 04:20 PM
python pandas


Whether it is business data analysis or data modeling. Data processing is an extremely important step, and it is crucial to the final result.
Today, I will summarize several important aspects of "Pandas data processing" for you. You can use it immediately and check it at any time.
  • Import data
  • Export data
  • View data
  • Data selection
  • Data processing
  • Data grouping and sorting
  • Data Merge
# 在使用之前,需要导入pandas库
import pandas as pd

Import data

Here I will summarize 7 common usages for you .
pd.DataFrame() # 自己创建数据框,用于练习

pd.read_csv(filename) # 从CSV⽂件导⼊数据

pd.read_table(filename) # 从限定分隔符的⽂本⽂件导⼊数据

pd.read_excel(filename) # 从Excel⽂件导⼊数据

pd.read_sql(query,connection_object) # 从SQL表/库导⼊数据

pd.read_json(json_string) # 从JSON格式的字符串导⼊数据

pd.read_html(url) # 解析URL、字符串或者HTML⽂件,抽取其中的tables表格

Export data

Here are 5 common uses.
df.to_csv(filename) #导出数据到CSV⽂件

df.to_excel(filename) #导出数据到Excel⽂件

df.to_sql(table_name,connection_object) #导出数据到SQL表

df.to_json(filename) #以Json格式导出数据到⽂本⽂件

writer=pd.ExcelWriter('test.xlsx',index=False) 
df1.to_excel(writer,sheet_name='单位')和writer.save(),将多个数据帧写⼊同⼀个⼯作簿的多个sheet(⼯作表)

View data

Here are 11 common usages summarized for you.
df.head(n) # 查看DataFrame对象的前n⾏

df.tail(n) # 查看DataFrame对象的最后n⾏

df.shape() # 查看⾏数和列数

df.info() # 查看索引、数据类型和内存信息

df.columns() # 查看字段(⾸⾏)名称

df.describe() # 查看数值型列的汇总统计

s.value_counts(dropna=False) # 查看Series对象的唯⼀值和计数

df.apply(pd.Series.value_counts) # 查看DataFrame对象中每⼀列的唯⼀值和计数

df.isnull().any() # 查看是否有缺失值

df[df[column_name].duplicated()] # 查看column_name字段数据重复的数据信息

df[df[column_name].duplicated()].count() # 查看column_name字段数据重复的个数

Data selection

Here are 10 common usages summarized for you.
df[col] # 根据列名,并以Series的形式返回列

df[[col1,col2]] # 以DataFrame形式返回多列

s.iloc[0] # 按位置选取数据

s.loc['index_one'] # 按索引选取数据

df.iloc[0,:] # 返回第⼀⾏

df.iloc[0,0] # 返回第⼀列的第⼀个元素

df.loc[0,:] # 返回第⼀⾏(索引为默认的数字时,⽤法同df.iloc),但需要注意的是loc是按索引,iloc参数只接受数字参数

df.ix[[:5],["col1","col2"]] # 返回字段为col1和col2的前5条数据,可以理解为loc和
iloc的结合体。

df.at[5,"col1"] # 选择索引名称为5,字段名称为col1的数据

df.iat[5,0] # 选择索引排序为5,字段排序为0的数据

数据处理

这里为大家总结16个常见用法。
df.columns= ['a','b','c'] # 重命名列名(需要将所有列名列出,否则会报错)

pd.isnull() # 检查DataFrame对象中的空值,并返回⼀个Boolean数组

pd.notnull() # 检查DataFrame对象中的⾮空值,并返回⼀个Boolean数组

df.dropna() # 删除所有包含空值的⾏

df.dropna(axis=1) # 删除所有包含空值的列

df.dropna(axis=1,thresh=n) # 删除所有⼩于n个⾮空值的⾏

df.fillna(value=x) # ⽤x替换DataFrame对象中所有的空值,⽀持

df[column_name].fillna(x)

s.astype(float) # 将Series中的数据类型更改为float类型

s.replace(1,'one') # ⽤‘one’代替所有等于1的值

s.replace([1,3],['one','three']) # ⽤'one'代替1,⽤'three'代替3

df.rename(columns=lambdax:x+1) # 批量更改列名

df.rename(columns={'old_name':'new_ name'}) # 选择性更改列名

df.set_index('column_one') # 将某个字段设为索引,可接受列表参数,即设置多个索引

df.reset_index("col1") # 将索引设置为col1字段,并将索引新设置为0,1,2...

df.rename(index=lambdax:x+1) # 批量重命名索引

数据分组、排序、透 视

这里为大家总结13个常见用法。
df.sort_index().loc[:5] # 对前5条数据进⾏索引排序

df.sort_values(col1) # 按照列col1排序数据,默认升序排列

df.sort_values(col2,ascending=False) # 按照列col1降序排列数据

df.sort_values([col1,col2],ascending=[True,False]) # 先按列col1升序排列,后按col2降序排列数据

df.groupby(col) # 返回⼀个按列col进⾏分组的Groupby对象

df.groupby([col1,col2]) # 返回⼀个按多列进⾏分组的Groupby对象

df.groupby(col1)[col2].agg(mean) # 返回按列col1进⾏分组后,列col2的均值,agg可以接受列表参数,agg([len,np.mean])

df.pivot_table(index=col1,values=[col2,col3],aggfunc={col2:max,col3:[ma,min]}) # 创建⼀个按列col1进⾏分组,计算col2的最⼤值和col3的最⼤值、最⼩值的数据透 视表

df.groupby(col1).agg(np.mean) # 返回按列col1分组的所有列的均值,⽀持

df.groupby(col1).col2.agg(['min','max'])

data.apply(np.mean) # 对DataFrame中的每⼀列应⽤函数np.mean

data.apply(np.max,axis=1) # 对DataFrame中的每⼀⾏应⽤函数np.max

df.groupby(col1).col2.transform("sum") # 通常与groupby连⽤,避免索引更改

数据合并

这里为大家总结5个常见用法。
df1.append(df2) # 将df2中的⾏添加到df1的尾部

df.concat([df1,df2],axis=1,join='inner') # 将df2中的列添加到df1的尾部,值为空的对应⾏与对应列都不要

df1.join(df2.set_index(col1),on=col1,how='inner') # 对df1的列和df2的列执⾏SQL形式的join,默认按照索引来进⾏合并,如果df1和df2有共同字段时,会报错,可通过设置lsuffix,rsuffix来进⾏解决,如果需要按照共同列进⾏合并,就要⽤到set_index(col1)

pd.merge(df1,df2,on='col1',how='outer') # 对df1和df2合并,按照col1,⽅式为outer

pd.merge(df1,df2,left_index=True,right_index=True,how='outer') # 与 df1.join(df2, how='outer')效果相同

The above is the detailed content of Summarized these 67 pandas functions, which perfectly solve data processing and are ready to use!. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1594
276
How to debug Python code in Sublime Text? How to debug Python code in Sublime Text? Aug 14, 2025 pm 04:51 PM

UseSublimeText’sbuildsystemtorunPythonscriptsandcatcherrorsbypressingCtrl Baftersettingthecorrectbuildsystemorcreatingacustomone.2.Insertstrategicprint()statementstocheckvariablevalues,types,andexecutionflow,usinglabelsandrepr()forclarity.3.Installth

How to run Python code in Sublime Text? How to run Python code in Sublime Text? Aug 16, 2025 am 04:58 AM

Make sure that Python is installed and added to the system PATH, run python--version or python3--version verification through the terminal; 2. Save the Python file as a .py extension, such as hello.py; 3. Create a custom build system in SublimeText, Windows users use {"cmd":["python","-u","$file"]}, macOS/Linux users use {"cmd":["python3

How to debug a Python script in VSCode How to debug a Python script in VSCode Aug 16, 2025 am 02:53 AM

To debug Python scripts, you need to first install the Python extension and configure the interpreter, then create a launch.json file to set the debugging configuration, then set a breakpoint in the code and press F5 to start the debugging. The script will be paused at the breakpoint, allowing checking variables and step-by-step execution. Finally, by checking the problem by viewing the console output, adding logs or adjusting parameters, etc., to ensure that the debugging process is simple and efficient after the environment is correct.

How to automatically format Python code in VSCode How to automatically format Python code in VSCode Aug 14, 2025 pm 04:10 PM

ToautomaticallyformatPythoncodeinVSCode,installBlackusingpipinstallblack,installtheofficialMicrosoftPythonextension,setBlackastheformatterinsettings.jsonwith"python.formatting.provider":"black",enableformatonsavebyadding"edit

What are class methods in Python What are class methods in Python Aug 21, 2025 am 04:12 AM

ClassmethodsinPythonareboundtotheclassandnottoinstances,allowingthemtobecalledwithoutcreatinganobject.1.Theyaredefinedusingthe@classmethoddecoratorandtakeclsasthefirstparameter,referringtotheclassitself.2.Theycanaccessclassvariablesandarecommonlyused

How to create a Python project in Sublime Text? How to create a Python project in Sublime Text? Aug 16, 2025 am 08:53 AM

InstallSublimeTextandPython,thenconfigureabuildsystembycreatingaPython3.sublime-buildfilewiththeappropriatecmdandselectorsettingstoenablerunningPythonscriptsviaCtrl B.2.OrganizeyourprojectbycreatingadedicatedfolderwithPythonfilesandsupportingdocument

python asyncio queue example python asyncio queue example Aug 21, 2025 am 02:13 AM

asyncio.Queue is a queue tool for secure communication between asynchronous tasks. 1. The producer adds data through awaitqueue.put(item), and the consumer uses awaitqueue.get() to obtain data; 2. For each item you process, you need to call queue.task_done() to wait for queue.join() to complete all tasks; 3. Use None as the end signal to notify the consumer to stop; 4. When multiple consumers, multiple end signals need to be sent or all tasks have been processed before canceling the task; 5. The queue supports setting maxsize limit capacity, put and get operations automatically suspend and do not block the event loop, and the program finally passes Canc

How does the yield keyword work in Python How does the yield keyword work in Python Aug 15, 2025 am 08:23 AM

The yield keyword is used to define a generator function, so that it can pause execution and return values one by one, and then recover from the pause; the generator function returns a generator object, has lazy evaluation characteristics, and can save memory. It is suitable for handling scenarios such as large files, streaming data, and infinite sequences. The generator is an iterator that supports next() and for loops, but cannot be rewind and must be recreated to iterate again.

See all articles