用Python Pandas操纵数据框架

用Python Pandas操纵数据框架

在用pandas操作数据框架之前,我们必须了解什么是数据操作。现实世界中的数据是非常不愉快和无序的,所以通过执行某些操作,我们可以根据自己的要求使数据变得可理解,这个将无序的数据转换成有意义的信息的过程可以通过数据操作来完成。

在这里,我们将学习如何用pandas来操作数据帧。Pandas是一个开源的库,从数据处理到数据分析,都是非常强大、灵活和易于使用的工具,可以用import pandas作为pd导入。Pandas主要处理一维和二维数组中的数据;尽管如此,Pandas处理这两种数据的方式不同。在pandas中,一维数组被表述为一个系列,而数据框架只是一个二维数组。这里使用的数据集是 country_code.csv 。

以下是用于操作数据框架的各种操作:

  • 首先,导入用于数据处理的库,即pandas,然后赋值并读取数据帧。
# import module
import pandas as pd
 
# assign dataset
df = pd.read_csv("country_code.csv")
 
# display
print("Type-", type(df))
df

输出:

用Pandas操纵数据框架--Python

  • 我们可以使用head()函数来读取数据框架,该函数也有一个参数(n),即要显示的行数。
df.head(10)

输出:

用Pandas操纵数据框架--Python

  • 使用shape()对DataFrame中的行和列进行计数。它返回包含在一个元组中的行和列的数量。
df.shape

输出:

用Pandas操纵数据框架--Python

  • 使用describe()方法对DataFrame进行统计的摘要。
df.describe()

输出:

用Pandas操纵数据框架--Python

  • 删除DataFrame中的缺失值,可以用dropna()方法来完成,它可以删除数据帧中所有的NaN值。
df.dropna()

输出:

用Pandas操纵数据框架--Python

另一个例子是:

df.dropna(axis=1)

这将放弃所有有任何缺失值的列。

输出:

用Pandas操纵数据框架--Python

  • 使用merge()合并数据帧,传递的参数是要合并的数据帧和列名。
df1 = pd.read_csv("country_code.csv")
merged_col = pd.merge(df, df1, on='Name')
merged_col

输出:

用Pandas操纵数据框架--Python

  • 一个额外的参数’on’是公共列的名称,这里’Name’是给merge()函数的公共列。 df是第一个数据框,df1是要合并的第二个数据框。
  • 使用rename()重命名数据框架的列,传递的参数是要重命名的列和原位。
country_code = df.rename(columns={'Name': 'CountryName',
                                  'Code': 'CountryCode'},
                         inplace=False)
country_code

输出:

用Pandas操纵数据框架--Python

代码’inplace = False’意味着结果将被存储在一个新的DataFrame中,而不是原来的那个。

  • 手动创建一个数据框架。
student = pd.DataFrame({'Name': ['Rohan', 'Rahul', 'Gaurav',
                                 'Ananya', 'Vinay', 'Rohan',
                                 'Vivek', 'Vinay'],
                         
                        'Score': [76, 69, 70, 88, 79, 64, 62, 57]})
 
# Reading Dataframe
student

输出:

用Pandas操纵数据框架--Python

  • 使用sort_values()方法对DataFrame进行排序。
student.sort_values(by=['Score'], ascending=True)

输出:

用Pandas操纵数据框架--Python

  • 使用多列对DataFrame进行排序。
student.sort_values(by=['Name', 'Score'],
                    ascending=[True, False])

输出:

用Pandas操纵数据框架--Python

  • 在DataFrame中创建另一列,这里我们将创建名为百分比的列,通过使用聚合函数sum()计算学生分数的百分比。
student['Percentage'] = (student['Score'] / student['Score'].sum()) * 100
student

输出:

用Pandas操纵数据框架--Python

  • 使用逻辑运算符选择DataFrame的行。
# Selecting rows where score is
# greater than 70
print(student[student.Score>70])
 
# Selecting rows where score is greater than 60
# OR less than 70
print(student[(student.Score>60) | (student.Score<70)])

输出:

用Pandas操纵数据框架--Python

  • 索引和切分 :

这里.loc是标签基础,.iloc是基于整数位置的方法,用于数据的切分和索引。

# Printing five rows with name column only
# i.e. printing first 5 student names.
print(student.loc[0:4, 'Name'])
 
# Printing all the rows with score column
# only i.e. printing score of all the
# students
print(student.loc[:, 'Score'])
 
# Printing only first rows having name,
# score columns i.e. print first student
# name & their score.
print(student.iloc[0, 0:2])
 
# Printing first 3 rows having name,score &
# percentage columns i.e. printing first three
# student name,score & percentage.
print(student.iloc[0:3, 0:3])
 
# Printing all rows having name & score
# columns i.e. printing all student
# name & their score.
print(student.iloc[:, 0:2])

输出:

.loc:

用Pandas操纵数据框架--Python

.iloc:

用Pandas操纵数据框架--Python

  • 应用函数,这个函数用来沿着数据框架的一个axis应用一个函数,无论它是行(axis=0)还是列(axis=1)。
# explicit function
def double(a):
    return 2*a
 
student['Score'] = student['Score'].apply(double)
 
# Reading Dataframe
student

输出:

用Pandas操纵数据框架--Python

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程