📜  如何利用 Pandas 数据框和系列进行数据整理?

📅  最后修改于: 2022-05-13 01:55:08.429000             🧑  作者: Mango

如何利用 Pandas 数据框和系列进行数据整理?

在本文中,我们将了解如何利用 Pandas DataFrame 和系列进行数据整理。

清理和集成脏且复杂的数据集以便于访问和分析的过程称为数据整理。随着数据量的不断增加和扩展,组织大量数据进行分析变得越来越重要。数据整理包括数据排序、数据过滤、数据缩减、数据访问和数据处理等活动。数据整理是数据科学和数据分析中最重要的任务之一。让我们看看如何利用 Pandas DataFrame 和 series 进行数据整理。

使用的 CSV: https://drive.google.com/file/d/1QK_0q4TjguwKjRMePk5NoQ29JcSfnGAe/view

利用系列进行数据整理

创建系列

pd.Series()方法用于创建熊猫系列。在此,一个列表作为参数给出,我们使用 index 参数来设置系列的索引。索引帮助我们根据条件检索数据。

Python3
# importing packages
import pandas as pd
  
# creating a series
population_data = pd.Series([1440297825, 1382345085,
                             331341050,
                             274021604, 212821986],
                            index=['China', 'India', 
                                   'United States',
                                   'Indonesia', 'Brazil'])
  
print(population_data)


Python3
print('population of india is : \
' + str(population_data['India']))
  
print('population greater than a billion :')
print(population_data[population_data > 1000000000])


Python3
population_data = pd.Series({'China': 1440297825,
                             'India': 1382345085, 
                             'United States': 331341050, 
                             'Indonesia': 274021604,
                             'Brazil': 212821986})
print(population_data)


Python3
population_data.index = ['CHINA','INDIA',
                         'US','INDONESIA',
                         'BRAZIL']
print(population_data)


Python3
# importing packages
import pandas as pd
  
# loading csv data
population_data = pd.read_csv('employees.csv')
  
# setting the index of the dataframe
population_data=population_data.set_index('First Name')
  
# head of the dataframe
population_data.head()


Python3
# importing packages
import pandas as pd
  
# loading csv data
population_data = pd.read_csv('employees.csv')
  
population_data.describe()


Python3
# importing packages
import pandas as pd
  
# creating a pandas Dataframe
population_data = pd.read_csv('employees.csv')
  
# setting the index of the dataframe
population_data = population_data.set_index('Start Date')
pd.DataFrame(population_data)


Python3
# importing packages
import pandas as pd
  
# creating a pandas Dataframe
population_data = pd.read_csv('employees.csv')
  
  
# resetting the index of the dataframe
population_data = population_data.reset_index()
  
population_data = population_data.set_index('First Name')
  
pd.DataFrame(population_data)


Python3
# importing packages
import pandas as pd
  
# loading csv data
population_data = pd.read_csv('employees.csv')
  
  
# deleting column
del population_data['Salary']
                      
pd.DataFrame(population_data.head())


Python3
# importing packages
import pandas as pd
  
# loading csv data
population_data = pd.read_csv('employees.csv')
  
# setting the index of the dataframe
population_data=population_data.set_index('First Name')
  
# displaying a transpose of the dataframe
pd.DataFrame(population_data.transpose().head())


Python3
# importing packages
import pandas as pd
  
# loading csv data
population_data = pd.read_csv('employees.csv')
  
# setting the index of the dataframe
population_data=population_data.set_index('First Name')
  
# sorting the Dataframe based on Density of population per km column
sorted_dataframe = population_data.sort_values('Salary', ascending=False)
pd.DataFrame(sorted_dataframe)


Python3
# importing packages
import pandas as pd
  
# loading csv data
data = pd.read_csv('employees.csv')
  
# checking for null values
data.isnull().sum()


Python3
# importing packages
import pandas as pd
  
# loading csv data
data = pd.read_csv('employees.csv')
  
# dropping NA values
data = data.dropna(axis=0, how='any')
  
# checking for null values
data.isnull().sum()


Python3
# importing pandas as pd
import pandas as pd
  
# Creating the dataframe
df = pd.read_csv("employees.csv")
  
# First grouping based on "Team"
# Within each team we are grouping based on "Position"
data = df.groupby(['First Name', 'Gender'])
  
# Print the first value in each group
data.first()


Python3
import pandas as pd
  
# reading two csv files
data = pd.read_csv('employees.csv')
  
# creating two dataframe 
head_data = data.head()
tail_data = data.tail()
  
# get top 5 rows
print("Head Data :")
display(head_data)
  
# get last 5 rows
print("Tail Data :")
display(tail_data)
  
# merge dataframke
merge_data = pd.merge(head_data, tail_data, how='outer' )
  
print("After merging: ")
display(merge_data)


Python3
import pandas as pd
  
# reading two csv files
data1 = pd.read_csv('employees.csv')
data2 = pd.read_csv('borrower.csv')
  
# contatenating the dataframes
pd.DataFrame(pd.concat([data1,data2]))


输出:

过滤数据 - 根据数据中的条件检索见解

从之前的数据中,我们检索到两个条件的数据,一个是印度的人口,另一个是人口超过 10 亿的国家。

Python3

print('population of india is : \
' + str(population_data['India']))
  
print('population greater than a billion :')
print(population_data[population_data > 1000000000])

输出:

我们还可以使用字典在Python中创建 Series。在此,我们必须将 Dictionary 作为参数传递给pd.Series()方法。

Python3

population_data = pd.Series({'China': 1440297825,
                             'India': 1382345085, 
                             'United States': 331341050, 
                             'Indonesia': 274021604,
                             'Brazil': 212821986})
print(population_data)

输出

通过更改系列的索引来更改索引

在 pd.Series 中,可以通过指定新的索引系列来操作或更改索引。

Python3

population_data.index = ['CHINA','INDIA',
                         'US','INDONESIA',
                         'BRAZIL']
print(population_data)

输出:

利用 Pandas Dataframe 进行数据整理

使用 CSV 创建数据框

在此示例中,我们将使用 CSV 文件使用 Pandas.head() 方法打印 DataFrame 或系列的前 n 行(默认为 5 行)。

Python3

# importing packages
import pandas as pd
  
# loading csv data
population_data = pd.read_csv('employees.csv')
  
# setting the index of the dataframe
population_data=population_data.set_index('First Name')
  
# head of the dataframe
population_data.head()

输出:

描述数据帧

pd.Describe()方法用于获取 Dataframe 的摘要统计信息。

Python3

# importing packages
import pandas as pd
  
# loading csv data
population_data = pd.read_csv('employees.csv')
  
population_data.describe()

输出:

设置和重置数据框的索引

pd.set_index用于设置和重置 Dataframe 的索引。而pd.reset_index()将 Dataframe 恢复到正常状态。在这里,列的名称作为参数给出。

示例 1:重置开始日期列中数据框的索引

Python3

# importing packages
import pandas as pd
  
# creating a pandas Dataframe
population_data = pd.read_csv('employees.csv')
  
# setting the index of the dataframe
population_data = population_data.set_index('Start Date')
pd.DataFrame(population_data)

输出:

示例 2:在 First Name 列中重置 Dataframe 的索引

Python3

# importing packages
import pandas as pd
  
# creating a pandas Dataframe
population_data = pd.read_csv('employees.csv')
  
  
# resetting the index of the dataframe
population_data = population_data.reset_index()
  
population_data = population_data.set_index('First Name')
  
pd.DataFrame(population_data)

输出:

从 DataFrame 中删除一列

从我们的 CSV 文件的 DataFrames 中删除了“Salary”列。

Python3

# importing packages
import pandas as pd
  
# loading csv data
population_data = pd.read_csv('employees.csv')
  
  
# deleting column
del population_data['Salary']
                      
pd.DataFrame(population_data.head())

输出:

重塑数据框

df.Transpose()函数用于查找给定 DataFrame 的转置。

Python3

# importing packages
import pandas as pd
  
# loading csv data
population_data = pd.read_csv('employees.csv')
  
# setting the index of the dataframe
population_data=population_data.set_index('First Name')
  
# displaying a transpose of the dataframe
pd.DataFrame(population_data.transpose().head())

输出:

对数据框进行排序

df.sort_values()函数用于对数据进行排序。在此,列名作为参数传递。

Python3

# importing packages
import pandas as pd
  
# loading csv data
population_data = pd.read_csv('employees.csv')
  
# setting the index of the dataframe
population_data=population_data.set_index('First Name')
  
# sorting the Dataframe based on Density of population per km column
sorted_dataframe = population_data.sort_values('Salary', ascending=False)
pd.DataFrame(sorted_dataframe)

输出:

处理缺失值

可以使用 Pandas df.null() 方法检查缺失值或空值。

Python3

# importing packages
import pandas as pd
  
# loading csv data
data = pd.read_csv('employees.csv')
  
# checking for null values
data.isnull().sum()

输出:

删除行

我们可以使用df.dropna()方法过滤具有空值的行。

Python3

# importing packages
import pandas as pd
  
# loading csv data
data = pd.read_csv('employees.csv')
  
# dropping NA values
data = data.dropna(axis=0, how='any')
  
# checking for null values
data.isnull().sum()

输出:

分组数据

在数据分析中,当结果必须用许多组来表示时,数据集的分组是一个常见的要求。 Panadas 为我们提供了一种内置机制,用于将数据分组为多个类别。 pandas 的 df.groupby() 技术用于对数据进行分组。

在下面的代码中,我们将创建一个学生及其成绩的 DataFrame。在此groupby()方法中,用于根据学生的成绩和姓名对学生进行分组。

Python3

# importing pandas as pd
import pandas as pd
  
# Creating the dataframe
df = pd.read_csv("employees.csv")
  
# First grouping based on "Team"
# Within each team we are grouping based on "Position"
data = df.groupby(['First Name', 'Gender'])
  
# Print the first value in each group
data.first()

输出:

合并数据框

Pandas df.merge()方法用于合并两个 DataFrame。合并 DataFrame 有多种方式,例如外连接、内连接、左连接、右连接等。

Python3

import pandas as pd
  
# reading two csv files
data = pd.read_csv('employees.csv')
  
# creating two dataframe 
head_data = data.head()
tail_data = data.tail()
  
# get top 5 rows
print("Head Data :")
display(head_data)
  
# get last 5 rows
print("Tail Data :")
display(tail_data)
  
# merge dataframke
merge_data = pd.merge(head_data, tail_data, how='outer' )
  
print("After merging: ")
display(merge_data)

输出:

连接数据

Concat函数用于沿轴进行连接操作。让我们创建两个 DataFrame 并将它们连接起来。

Python3

import pandas as pd
  
# reading two csv files
data1 = pd.read_csv('employees.csv')
data2 = pd.read_csv('borrower.csv')
  
# contatenating the dataframes
pd.DataFrame(pd.concat([data1,data2]))

输出: