Home Backend Development Python Tutorial The most complete summary of Python pandas usage

The most complete summary of Python pandas usage

Aug 03, 2019 pm 05:57 PM
pandas python Summarize

The most complete summary of Python pandas usage

1. Generate data table

1. First import the pandas library. Generally, the numpy library is used, so Let’s import the backup first:

import numpy as np
import pandas as pd
Copy after login

2. Import CSV or xlsx file:

df = pd.DataFrame(pd.read_csv('name.csv',header=1))
df = pd.DataFrame(pd.read_excel('name.xlsx'))
Copy after login

3. Use pandas to create a data table:

df = pd.DataFrame({"id":[1001,1002,1003,1004,1005,1006], 
 "date":pd.date_range('20130102', periods=6),
 "city":['Beijing ', 'SH', ' guangzhou ', 'Shenzhen', 'shanghai', 'BEIJING '],
 "age":[23,44,54,32,34,32],
 "category":['100-A','100-B','110-A','110-C','210-A','130-F'],
 "price":[1200,np.nan,2133,5433,np.nan,4432]},
columns =['id','date','city','category','age','price'])
Copy after login

2. Data table information View

1. Dimension view:

df.shape
Copy after login

2. Basic information of the data table (dimension, column name, data format, occupied space, etc.):

df.info()
Copy after login

3. The format of each column of data:

df.dtypes
Copy after login

4. The format of a certain column:

df['B'].dtype
Copy after login

5. Null value:

df.isnull()
Copy after login
Copy after login

6. View the null value of a certain column:

df.isnull()
Copy after login
Copy after login

7. View the unique value of a column:

df['B'].unique()
Copy after login

8. View the value of the data table:

df.values
Copy after login

9. View the column name:

df.columns
Copy after login

10 , View the first 10 rows of data and the last 10 rows of data:

df.head() #默认前10行数据
df.tail()    #默认后10 行数据
Copy after login

Related recommendations: "Python Video Tutorial"

3. Data table cleaning

1. Fill the empty values ​​with the number 0:

df.fillna(value=0)
Copy after login

2. Use the mean value of the column prince to fill the NA:

df['prince'].fillna(df['prince'].mean())
Copy after login

3. Clear the character spaces in the city field:

df['city']=df['city'].map(str.strip)
Copy after login

4. Case conversion:

df['city']=df['city'].str.lower()
Copy after login

5. Change data format:

df['price'].astype('int')
Copy after login

6. Change column name:

df.rename(columns={'category': 'category-size'})
Copy after login

7. After deletion Duplicate values ​​that appear:

df['city'].drop_duplicates()
Copy after login

8. Delete duplicate values ​​that appear first:

df['city'].drop_duplicates(keep='last')
Copy after login

9. Data replacement:

df['city'].replace('sh', 'shanghai')
Copy after login

4. Data preprocessing

df1=pd.DataFrame({"id":[1001,1002,1003,1004,1005,1006,1007,1008], 
"gender":['male','female','male','female','male','female','male','female'],
"pay":['Y','N','Y','Y','N','Y','N','Y',],
"m-point":[10,12,20,40,40,40,30,20]})
Copy after login

1. Merge data tables

df_inner=pd.merge(df,df1,how='inner')  # 匹配合并,交集
df_left=pd.merge(df,df1,how='left')        #
df_right=pd.merge(df,df1,how='right')
df_outer=pd.merge(df,df1,how='outer')  #并集
Copy after login

2. Set index columns

df_inner.set_index('id')
Copy after login

3. Sort by the value of a specific column:

df_inner.sort_values(by=['age'])
Copy after login

4. Sort by index column:

df_inner.sort_index()
Copy after login

5. If the value of the prince column is >3000, the group column displays high, otherwise it displays low:

df_inner['group'] = np.where(df_inner['price'] > 3000,'high','low')
Copy after login

6. Group data that combines multiple conditions Mark

df_inner.loc[(df_inner['city'] == 'beijing') & (df_inner['price'] >= 4000), 'sign']=1
Copy after login

7. Sort the values ​​of the category field into columns in sequence and create a data table. The index value is the index column of df_inner. The column names are category and size

pd.DataFrame((x.split('-') for x in df_inner['category']),index=df_inner.index,columns=['category','size']))
Copy after login

8. It will be completed. Match the split data table with the original df_inner data table

df_inner=pd.merge(df_inner,split,right_index=True, left_index=True)
Copy after login

5. Data extraction

The three main functions used: loc, iloc and ix, loc The function extracts by label value, iloc extracts by position, and ix can extract by label and position at the same time.

1. Extract the value of a single row by index

df_inner.loc[3]
Copy after login

2. Extract the value of a regional row by index

df_inner.iloc[0:5]
Copy after login

3. Reset the index

df_inner.reset_index()
Copy after login

4. Set date as index

df_inner=df_inner.set_index('date')
Copy after login

5. Extract all data before 4 days

df_inner[:'2013-01-04']
Copy after login

6. Use iloc to extract data by location area

df_inner.iloc[:3,:2] #冒号前后的数字不再是索引的标签名称,而是数据所在的位置,从0开始,前三行,前两列。
Copy after login

7. Adapt iloc individually by location File data

df_inner.iloc[[0,2,5],[4,5]] #提取第0、2、5行,4、5列
Copy after login

8. Use ix to extract data by index label and position mixture

df_inner.ix[:'2013-01-03',:4] #2013-01-03号之前,前四列数据
Copy after login

9. Determine whether the value of the city column is Beijing

df_inner['city'].isin(['beijing'])
Copy after login

10. Determine the city column contains beijing and shanghai, and then extract the data that meets the conditions

df_inner.loc[df_inner['city'].isin(['beijing','shanghai'])]
Copy after login

11. Extract the first three characters and generate a data table

pd.DataFrame(category.str[:3])
Copy after login

6. Data filtering

Use the three conditions of AND, OR, NOT and greater than, less than, and equal to filter the data, and perform counting and summing.

1. Use "AND" to filter

df_inner.loc[(df_inner['age'] > 25) & (df_inner['city'] == 'beijing'), ['id','city','age','category','gender']]
Copy after login

2. Use "OR" to filter

df_inner.loc[(df_inner['age'] > 25) | (df_inner['city'] == 'beijing'), ['id','city','age','category','gender']]
.sort(['age'])
Copy after login

3. Use "NOT" condition to filter

df_inner.loc[(df_inner['city'] != 'beijing'), ['id','city','age','category','gender']].sort(['id'])
Copy after login

4. Count the filtered data by city column

df_inner.loc[(df_inner['city'] != 'beijing'), ['id','city','age','category','gender']].sort(['id']).city.count()
Copy after login

5. Use query function to filter

df_inner.query('city == ["beijing", "shanghai"]')
Copy after login

6. Sum the filtered results by prince

df_inner.query('city == ["beijing", "shanghai"]').price.sum()
Copy after login

7. Data summary

The main functions are groupby and pivot_table

1. Count and summarize all columns

df_inner.groupby('city').count()
Copy after login

2. Count the id field by city

df_inner.groupby('city')['id'].count()
Copy after login

3. Summarize the two fields

df_inner.groupby(['city','size'])['id'].count()
Copy after login

4. Summarize the city field and calculate the total and mean of prince respectively

df_inner.groupby('city')['price'].agg([len,np.sum, np.mean])
Copy after login

8. Data statistics

Data sampling, calculation of standard deviation, covariance and correlation coefficient

1. Simple data sampling

df_inner.sample(n=3)
Copy after login

2. Manually set the sampling weight

weights = [0, 0, 0, 0, 0.5, 0.5]
df_inner.sample(n=2, weights=weights)
Copy after login

3. No replacement after sampling

df_inner.sample(n=6, replace=False)
Copy after login

4. Replacement after sampling

df_inner.sample(n=6, replace=True)
Copy after login

5. Descriptive statistics of data table

df_inner.describe().round(2).T #round函数设置显示小数位,T表示转置
Copy after login

6. Calculate the standard deviation of a column

df_inner['price'].std()
Copy after login

7. Calculate the covariance between two fields

df_inner['price'].cov(df_inner['m-point'])
Copy after login

8. Calculate the covariance between all fields in the data table

df_inner.cov()
Copy after login

9. Correlation analysis of two fields

df_inner['price'].corr(df_inner['m-point']) #相关系数在-1到1之间,接近1为正相关,接近-1为负相关,0为不相关
Copy after login

10. Correlation analysis of data table

df_inner.corr()
Copy after login

9. Data output

The analyzed data can be output to xlsx format and csv format

1, written to Excel

df_inner.to_excel('excel_to_python.xlsx', sheet_name='bluewhale_cc')
Copy after login

2, written to CSV

df_inner.to_csv('excel_to_python.csv')
Copy after login

The above is the detailed content of The most complete summary of Python pandas usage. 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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

See all articles