search
HomeBackend DevelopmentPython TutorialPython data cleaning: data merging, conversion, filtering and sorting

Earlier we used pandas to perform some basic operations. Next, we will learn more about data operations.

Data cleaning has always been an extremely important part of data analysis.

Data merging

In pandas, data can be merged through merge.

import numpy as np
import pandas as pd
data1 = pd.DataFrame({'level':['a','b','c','d'],
         'numeber':[1,3,5,7]})

data2=pd.DataFrame({'level':['a','b','c','e'],
         'numeber':[2,3,6,10]})
print(data1)

The result is:

python 数据清洗之数据合并、转换、过滤、排序

##

print(data2)

The result is:


python 数据清洗之数据合并、转换、过滤、排序

##
print(pd.merge(data1,data2))

The result is:


python 数据清洗之数据合并、转换、过滤、排序
You can see that the fields used for the same label in data1 and data2 are displayed, while other fields are discarded. This is equivalent to the inner join connection operation in SQL.

In addition, there are connection methods such as outer, ringt, left, etc., which are represented by the keyword how.


data3 = pd.DataFrame({'level1':['a','b','c','d'],
         'numeber1':[1,3,5,7]})
data4=pd.DataFrame({'level2':['a','b','c','e'],
         'numeber2':[2,3,6,10]})
print(pd.merge(data3,data4,left_on='level1',right_on='level2'))

The result is:


python 数据清洗之数据合并、转换、过滤、排序
If the column in the two data frames When the names are different, we can connect the data together by specifying the two parameters letf_on and right_on

print(pd.merge(data3,data4,left_on='level1',right_on='level2',how='left'))

The result is:


python 数据清洗之数据合并、转换、过滤、排序Other detailed parameter description


python 数据清洗之数据合并、转换、过滤、排序

Overlapping data merging

Sometimes We will encounter overlapping data that needs to be merged. In this case, we can use the comebine_first function.

data3 = pd.DataFrame({'level':['a','b','c','d'],
         'numeber1':[1,3,5,np.nan]})
 data4=pd.DataFrame({'level':['a','b','c','e'],
         'numeber2':[2,np.nan,6,10]})
 print(data3.combine_first(data4))

The result is:


python 数据清洗之数据合并、转换、过滤、排序
You can see the results under the same tag The content of data3 is displayed first. If a certain data in a data frame is missing, the elements in another data frame will be filled in.


The usage here is similar to np.where (isnull(a),b,a)

Data reshaping and axial rotation

We mentioned this content in the previous pandas article. Data reshaping mainly uses the reshape function, and rotation mainly uses the unstack and stack functions.

data=pd.DataFrame(np.arange(12).reshape(3,4),
       columns=['a','b','c','d'],
       index=['wang','li','zhang'])
print(data)

The result is:


python 数据清洗之数据合并、转换、过滤、排序##

print(data.unstack())

The result is:


python 数据清洗之数据合并、转换、过滤、排序Data conversion

Delete duplicate row data

data=pd.DataFrame({'a':[1,3,3,4],
       'b':[1,3,3,5]})
print(data)

The result is:


python 数据清洗之数据合并、转换、过滤、排序

print(data.duplicated())

The result is:


python 数据清洗之数据合并、转换、过滤、排序It can be seen that the third row repeats the data of the second row, so the displayed result is True

另外用drop_duplicates方法可以去除重复行

print(data.drop_duplicates())

结果为:
python 数据清洗之数据合并、转换、过滤、排序

替换值

除了使用我们上一篇文章中提到的fillna的方法外,还可以用replace方法,而且更简单快捷

data=pd.DataFrame({'a':[1,3,3,4],
       'b':[1,3,3,5]})
print(data.replace(1,2))

结果为:

python 数据清洗之数据合并、转换、过滤、排序

多个数据一起换

print(data.replace([1,4],np.nan))

python 数据清洗之数据合并、转换、过滤、排序

数据分段


data=[11,15,18,20,25,26,27,24]
bins=[15,20,25]
print(data)
print(pd.cut(data,bins))

结果为:
[11, 15, 18, 20, 25, 26, 27, 24][NaN, NaN, (15, 20], (15, 20], (20, 25], NaN, NaN, (20, 25]]
Categories (2, object): [(15, 20]

可以看出分段后的结果,不在分段内的数据显示为na值,其他则显示数据所在的分段。

print(pd.cut(data,bins).labels)

结果为:

[-1 -1 0 0 1 -1 -1 1]

显示所在分段排序标签

print(pd.cut(data,bins).levels)

结果为:

Index([‘(15, 20]', ‘(20, 25]'], dtype='object')

显示所以分段标签

print(value_counts(pd.cut(data,bins)))

结果为:

python 数据清洗之数据合并、转换、过滤、排序

显示每个分段值得个数

此外还有一个qcut的函数可以对数据进行4分位切割,用法和cut类似。

排列和采样

我们知道排序的方法有好几个,比如sort,order,rank等函数都能对数据进行排序
现在要说的这个是对数据进行随机排序(permutation)

data=np.random.permutation(5)
print(data)

结果为:

[1 0 4 2 3]

这里的peemutation函数对0-4的数据进行随机排序的结果。
也可以对数据进行采样

df=pd.DataFrame(np.arange(12).reshape(4,3))
samp=np.random.permutation(3)
print(df)

结果为:

python 数据清洗之数据合并、转换、过滤、排序

print(samp)

结果为:
[1 0 2]

print(df.take(samp))

结果为:

python 数据清洗之数据合并、转换、过滤、排序

这里使用take的结果是,按照samp的顺序从df中提取样本。

更多python 数据清洗之数据合并、转换、过滤、排序相关文章请关注PHP中文网!

Statement
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
How do you create multi-dimensional arrays using NumPy?How do you create multi-dimensional arrays using NumPy?Apr 29, 2025 am 12:27 AM

Create multi-dimensional arrays with NumPy can be achieved through the following steps: 1) Use the numpy.array() function to create an array, such as np.array([[1,2,3],[4,5,6]]) to create a 2D array; 2) Use np.zeros(), np.ones(), np.random.random() and other functions to create an array filled with specific values; 3) Understand the shape and size properties of the array to ensure that the length of the sub-array is consistent and avoid errors; 4) Use the np.reshape() function to change the shape of the array; 5) Pay attention to memory usage to ensure that the code is clear and efficient.

Explain the concept of 'broadcasting' in NumPy arrays.Explain the concept of 'broadcasting' in NumPy arrays.Apr 29, 2025 am 12:23 AM

BroadcastinginNumPyisamethodtoperformoperationsonarraysofdifferentshapesbyautomaticallyaligningthem.Itsimplifiescode,enhancesreadability,andboostsperformance.Here'showitworks:1)Smallerarraysarepaddedwithonestomatchdimensions.2)Compatibledimensionsare

Explain how to choose between lists, array.array, and NumPy arrays for data storage.Explain how to choose between lists, array.array, and NumPy arrays for data storage.Apr 29, 2025 am 12:20 AM

ForPythondatastorage,chooselistsforflexibilitywithmixeddatatypes,array.arrayformemory-efficienthomogeneousnumericaldata,andNumPyarraysforadvancednumericalcomputing.Listsareversatilebutlessefficientforlargenumericaldatasets;array.arrayoffersamiddlegro

Give an example of a scenario where using a Python list would be more appropriate than using an array.Give an example of a scenario where using a Python list would be more appropriate than using an array.Apr 29, 2025 am 12:17 AM

Pythonlistsarebetterthanarraysformanagingdiversedatatypes.1)Listscanholdelementsofdifferenttypes,2)theyaredynamic,allowingeasyadditionsandremovals,3)theyofferintuitiveoperationslikeslicing,but4)theyarelessmemory-efficientandslowerforlargedatasets.

How do you access elements in a Python array?How do you access elements in a Python array?Apr 29, 2025 am 12:11 AM

ToaccesselementsinaPythonarray,useindexing:my_array[2]accessesthethirdelement,returning3.Pythonuseszero-basedindexing.1)Usepositiveandnegativeindexing:my_list[0]forthefirstelement,my_list[-1]forthelast.2)Useslicingforarange:my_list[1:5]extractselemen

Is Tuple Comprehension possible in Python? If yes, how and if not why?Is Tuple Comprehension possible in Python? If yes, how and if not why?Apr 28, 2025 pm 04:34 PM

Article discusses impossibility of tuple comprehension in Python due to syntax ambiguity. Alternatives like using tuple() with generator expressions are suggested for creating tuples efficiently.(159 characters)

What are Modules and Packages in Python?What are Modules and Packages in Python?Apr 28, 2025 pm 04:33 PM

The article explains modules and packages in Python, their differences, and usage. Modules are single files, while packages are directories with an __init__.py file, organizing related modules hierarchically.

What is docstring in Python?What is docstring in Python?Apr 28, 2025 pm 04:30 PM

Article discusses docstrings in Python, their usage, and benefits. Main issue: importance of docstrings for code documentation and accessibility.

See all articles

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor