Pandas基本操作

文章目录


第1关:了解数据处理对象--Series

任务描述

本关任务:仔细阅读编程要求,完成相关要求。

相关知识

为了完成本关任务,你需要掌握:

Pandas 中的数据结构;

了解 Series。

Pandas 是为了解决数据分析任务而创建的,纳入了大量的库和标准数据模型,提供了高效地操作大型数据集所需的工具。

对于 Pandas 包,在 Python 中常见的导入方法如下:

python 复制代码
from pandas import Series,DataFrame
import pandas as pd

Pandas 中的数据结构

Series: 一维数组,类似于 Python 中的基本数据结构 list,区别是 Series 只允许存储相同的数据类型,这样可以更有效的使用内存,提高运算效率。就像数据库中的列数据;

DataFrame: 二维的表格型数据结构。很多功能与 R 中的 data.frame 类似。可以将 DataFrame 理解为 Series 的容器;

Panel:三维的数组,可以理解为 DataFrame 的容器。

了解 Series

为了开始使用 Pandas,我们必需熟悉它的两个重要的数据结构: Series 和 DataFrame。虽然它们不是每一个问题的通用解决方案,但可以提供一个坚实的,易于使用的大多数应用程序的基础。

Series 是一个一维的类似的数组对象,包含一个数组的数据(任何 NumPy 的数据类型)和一个与数组关联的数据标签,被叫做索引 。最简单的 Series 是由一个数组的数据构成:

python 复制代码
In [1]:obj=Series([4,7,-5,3])
In [2]:obj
Out[2]:
0 4
1 7
2 -5
3 3

Series 的交互式显示的字符串表示形式是索引在左边,值在右边。因为我们没有给数据指定索引,一个包含整数 0 到 N-1 这里 N 是数据的长度)的默认索引被创建。你可以分别的通过它的 values 和 index 属性来获取 Series 的数组表示和索引对象:

python 复制代码
In [3]: obj.values
Out[3]:array([4,7,-5,3])
In [4]: obj.index
Out[4]:Int64Index([0,1,2,3])

通常,需要创建一个带有索引来确定每一个数据点的 Series。

python 复制代码
In [5]:obj2=Series([4,7,-5,3],index=['d','b','a','c'])
In [6]:obj2
Out[6]:
d 4
b 7
a -5
c 3

如果你有一些数据在一个 Python 字典中,你可以通过传递字典来从这些数据创建一个 Series,只传递一个字典的时候,结果 Series 中的索引将是排序后的字典的键。

python 复制代码
In [7]:sdata={'Ohio':35000,'Texas':71000,'Oregon':16000,'Utah':5000}
In [8]:obj3=Series(sdata)
In [9]:obj3
Out[9]:
Ohio   35000
Texas  71000
Oregon 16000
Utah   5000

编程要求

根据提示,在右侧编辑器 Begin-End 内补充代码:

创建一个名为 series_a 的 series 数组,当中值为 [1,2,5,7],对应的索引为 ['nu', 'li', 'xue', 'xi'];

创建一个名为 dict_a 的字典,字典中包含如下内容 {'ting':1, 'shuo':2, 'du':32, 'xie':44};

将 dict_a 字典转化成名为 series_b 的 series 数组。

测试说明

如果答案正确,则会输出 True。

开始你的任务吧,祝你成功!

示例代码如下:

python 复制代码
# -*- coding: utf-8 -*-
from pandas import Series,DataFrame
import  pandas as pd
 
def create_series():
    '''
    返回值:
    series_a: 一个Series类型数据
    series_b: 一个Series类型数据
    dict_a:  一个字典类型数据
    '''
    # 请在此添加代码 完成本关任务
    # ********** Begin *********#
    series_a=Series([1,2,5,7],index=['nu','li','xue','xi'])
    dict_a={'ting':1, 'shuo':2, 'du':32, 'xie':44}
    series_b=Series(dict_a)
    # ********** End **********#
 
    # 返回series_a,dict_a,series_b
    return series_a,dict_a,series_b

第2关:了解数据处理对象-DataFrame

任务描述

本关任务:根据编程要求,完成相关代码的编写。

相关知识

为了完成本关任务,你需要掌握:

DataFrame 创建;

修改行名;

添加修改;

添加 Series 类型;

添加新列。

DataFrame 是一个表格型的数据结构,是以一个或多个二维块存放的数据表格(层次化索引),DataFrame 既有行索引还有列索引,它有一组有序的列,每列既可以是不同类型(数值、字符串、布尔型)的数据,或者可以看做由 Series 组成的字典。

DataFrame 创建

dictionary = {'state':['0hio','0hio','0hio','Nevada','Nevada'],

'year':[2000,2001,2002,2001,2002],

'pop':[1.5,1.7,3.6,2.4,2.9]}

frame = DataFrame(dictionary)

修改行名

frame=DataFrame(dictionary,index=['one','two','three','four','five'])

添加修改

frame['add']=[0,0,0,0,0]

添加 Series 类型

value = Series([1,3,1,4,6,8],index = [0,1,2,3,4,5])

frame['add1'] = value

添加新列

1、直接在后面新增一列

指明列名,并赋值即可:

data['列名']=[1,2]

2、在指定位置新增一列

用insert()函数,data.insert(位置,列名,列值),例如:

data.insert(2,'c','')

编程要求

根据提示,在右侧编辑器 Begin-End 内补充代码:

创建一个五行三列的名为 df1 的 DataFrame 数组,列名为 [states,years,pops],行名 ['one','two','three','four','five'];

给 df1 添加新列,列名为 new_add,值为 [7,4,5,8,2]。

测试说明

如果答案正确,则会输出 True。

开始你的任务吧,祝你成功!

示例代码如下:

python 复制代码
# -*- coding: utf-8 -*-
from pandas import Series,DataFrame
import  pandas as pd
 
def create_dataframe():
    '''
    返回值:
    df1: 一个DataFrame类型数据
    '''
    # 请在此添加代码 完成本关任务
    # ********** Begin *********#
    dictionary = {'states':['0hio','0hio','0hio','Nevada','Nevada'],
         'years':[2000,2001,2002,2001,2002],
         'pops':[1.5,1.7,3.6,2.4,2.9]}
    df1 = DataFrame(dictionary)
    df1=DataFrame(dictionary,index=['one','two','three','four','five'])
    df1['new_add']=[7,4,5,8,2]
    # ********** End **********#
 
    #返回df1
    return df1

第3关:读取 CSV 格式数据

任务描述

本关任务:根据编程要求,完成相关代码的编写。

相关知识

为了完成本关任务,你需要掌握:

读取 CSV;

查看前 n 行;

查看后 n 行;

查看总行数;

修改列名。

在使用机器学习工具包对数据进行修改、探索和分析之前,我们必须先讲外部数据导入。使用 Pandas 导入数据比 Numpy 要容易。在这里我们将使用英国降雨数据,数据已下好并放在本实训的当前文件夹。

python 复制代码
读取 CSV
# Reading a csv into Pandas.
# 如果数据集中有中文的话,最好在里面加上 encoding = 'gbk' ,以避免乱码问题。后面的导出数据的时候也一样。
df = pd.read_csv('uk_rain_2014.csv', header=0)

这里我们从 csv 文件里导入了数据,并储存在 DataFrame 中。这一步非常简单,你只需要调用 read_csv 然后将文件的路径传进去就行了。header 关键字告诉 Pandas 哪些是数据的列名。如果没有列名的话就将它设定为 None。

数据导入 pandas 之后,我们该怎么查看数据呢?

python 复制代码
查看前 n 行
# Getting first x rows.
df.head(5)
查看后 n 行
# Getting last x rows.
df.tail(5)
查看总行数
# Finding out how many rows dataset has.
len(df)
修改列名
我们通常使用列的名字来在 Pandas 中查找列。这一点很好而且易于使用,但是有时列名太长,我们需要缩短列名。

    # Changing column labels.
    df.columns = ['water_year','rain_octsep','outflow_octsep','rain_decfeb', 'outflow_decfeb', 'rain_junaug', 'outflow_junaug']

编程要求

根据提示,在右侧编辑器 Begin-End 内补充代码:

将 test3/uk_rain_2014.csv 中的数据导入到 df1 中;

python 复制代码
将列名修改为 ['water_year','rain_octsep','outflow_octsep','rain_decfeb', 'outflow_decfeb', 'rain_junaug', 'outflow_junaug'];

计算 df1 的总行数并存储在 length1 中。

测试说明

如果答案正确,则会输出 True。

开始你的任务吧,祝你成功!

示例代码如下:

python 复制代码
# -*- coding: utf-8 -*-
from pandas import Series,DataFrame
import  pandas as pd
def read_csv_data():
    '''
    返回值:
    df1: 一个DataFrame类型数据
    length1: 一个int类型数据
    '''
    # 请在此添加代码 完成本关任务
    # ********** Begin *********#
    df1 = pd.read_csv('test3/uk_rain_2014.csv', header=0)
    df1.columns = ['water_year','rain_octsep','outflow_octsep','rain_decfeb', 'outflow_decfeb', 'rain_junaug', 'outflow_junaug']
    length1=len(df1)
    # ********** End **********#
    #返回df1,length1
    return df1,length1

第4关:数据的基本操作------排序

任务描述

本关任务:根据编程要求,完成相关代码的编写。

相关知识

为了完成本关任务,你需要掌握:

对索引进行排序;

按行排序;

按值排序。

本关我们将学习处理 Series 和 DataFrame 中的数据的基本手段,我们将会探讨 Pandas 最为重要的一些功能。

对索引进行排序

python 复制代码
Series 用 sort_index() 按索引排序,sort_values() 按值排序;
DataFrame 也是用 sort_index() 和 sort_values()。

In[73]: obj = Series(range(4), index=['d','a','b','c'])
In[74]: obj.sort_index()  
Out[74]: 
a    1
b    2
c    3
d    0
dtype: int64
In[78]: frame = DataFrame(np.arange(8).reshape((2,4)),index=['three', 'one'],columns=['d','a','b','c'])
In[79]: frame
Out[79]: 
       d  a  b  c
three  0  1  2  3
one    4  5  6  7
In[86]: frame.sort_index()
Out[86]: 
       d  a  b  c
one    4  5  6  7
three  0  1  2  3
按行排序
In[89]: frame.sort_index(axis=1, ascending=False)
Out[89]: 
       d  c  b  a
three  0  3  2  1
one    4  7  6  5
按值排序
Series:

In[92]: obj = Series([4, 7, -3, 2])
In[94]: obj.sort_values()
Out[94]: 
2   -3
3    2
0    4
1    7
dtype: int64
DataFrame:

In[95]: frame = DataFrame({'b':[4, 7, -3, 2], 'a':[0, 1, 0, 1]})
In[97]: frame.sort_values(by='b')  #DataFrame必须传一个by参数表示要排序的列
Out[97]: 
   a  b
2  0 -3
3  1  2
0  0  4
1  1  7

编程要求

根据提示,在右侧编辑器 Begin-End 内补充代码:

对代码中 s1 进行按索引排序,并将结果存储到 s2;

对代码中 d1 进行按值排序(index 为 f),并将结果存储到 d2。

测试说明

如果答案正确,则会输出 True。

示例代码如下:

python 复制代码
# -*- coding: utf-8 -*-
from pandas import Series,DataFrame
import  pandas as pd
def sort_gate():
    '''
    返回值:
    s2: 一个Series类型数据
    d2: 一个DataFrame类型数据
    '''
 
    # s1是Series类型数据,d1是DataFrame类型数据
    s1 = Series([4, 3, 7, 2, 8], index=['z', 'y', 'j', 'i', 'e'])
    d1 = DataFrame({'e': [4, 2, 6, 1], 'f': [0, 5, 4, 2]})
 
    # 请在此添加代码 完成本关任务
    # ********** Begin *********#
    s2=s1.sort_index()
    d2=d1.sort_values(by='f')
    # ********** End **********#
 
    #返回s2,d2
    return s2,d2

第5关:数据的基本操作------删除

任务描述

本关任务:根据编程要求,完成相关代码的编写。

相关知识

为了完成本关任务,你需要掌握:删除指定轴上的项。

python 复制代码
删除指定轴上的项
即删除 Series 的元素或 DataFrame 的某一行(列)的意思,我们可以通过对象的 drop(labels, axis=0) 方法实现此功能。

删除 Series 的一个元素:

In[11]: ser = Series([4.5,7.2,-5.3,3.6], index=['d','b','a','c'])
In[13]: ser.drop('c')
Out[13]: 
d    4.5
b    7.2
a   -5.3
dtype: float64
删除 DataFrame 的行或列:

In[17]: df = DataFrame(np.arange(9).reshape(3,3), index=['a','c','d'], columns=['oh','te','ca'])
In[18]: df
Out[18]: 
   oh  te  ca
a   0   1   2
c   3   4   5
d   6   7   8
In[19]: df.drop('a')
Out[19]: 
   oh  te  ca
c   3   4   5
d   6   7   8
In[20]: df.drop(['oh','te'],axis=1)
Out[20]: 
   ca
a   2
c   5
d   8
需要注意的是 drop() 返回的是一个新对象,原对象不会被改变。

编程要求

根据提示,在右侧编辑器 Begin-End 内补充代码:

在 s1 中删除 z 行,并赋值到 s2;

d1 中删除 yy 列,并赋值到 d2。

测试说明

如果答案正确,则会输出 True。

示例代码如下:

python 复制代码
# -*- coding: utf-8 -*-
from pandas import Series,DataFrame
import numpy as np
import  pandas as pd
 
def delete_data():
    '''
    返回值:
    s2: 一个Series类型数据
    d2: 一个DataFrame类型数据
    '''
 
    # s1是Series类型数据,d1是DataFrame类型数据
    s1 = Series([5, 2, 4, 1], index=['v', 'x', 'y', 'z'])
    d1=DataFrame(np.arange(9).reshape(3,3), columns=['xx','yy','zz'])
    # 请在此添加代码 完成本关任务
    # ********** Begin *********#
    s2=s1.drop('z')
    d2=d1.drop(['yy'],axis=1)
    # ********** End **********#
 
    # 返回s2,d2
    return s2, d2

第6关:数据的基本操作------算术运算

任务描述

本关任务:根据编程要求,完成相关代码的编写。

相关知识

为了完成本关任务,你需要掌握:算术运算(+,-,*,/)。

算术运算(+,-,*,/)

DataFrame 中的算术运算是 df 中对应位置的元素的算术运算,如果没有共同的元素,则用 NaN 代替。

python 复制代码
In[5]: df1 = DataFrame(np.arange(12.).reshape((3,4)),columns=list('abcd'))
In[6]: df2 = DataFrame(np.arange(20.).reshape((4,5)),columns=list('abcde'))
In[9]: df1+df2
Out[9]: 
    a   b   c   d   e
0   0   2   4   6 NaN
1   9  11  13  15 NaN
2  18  20  22  24 NaN
3 NaN NaN NaN NaN NaN

此外,如果我们想设置默认的其他填充值,而非 NaN 的话,可以传入填充值。

python 复制代码
In[11]: df1.add(df2, fill_value=0)
Out[11]: 
    a   b   c   d   e
0   0   2   4   6   4
1   9  11  13  15   9
2  18  20  22  24  14
3  15  16  17  18  19

编程要求

根据提示,在右侧编辑器 Begin-End 内补充代码:

让 df1 与 df2 相加得到 df3,并设置默认填充值为 4。

测试说明

如果答案正确,则会输出 True。

开始你的任务吧,祝你成功!

示例代码如下:

python 复制代码
# -*- coding: utf-8 -*-
from pandas import Series,DataFrame
import numpy as np
import  pandas as pd
 
def add_way():
    '''
    返回值:
    df3: 一个DataFrame类型数据
    '''
 
    # df1,df2是DataFrame类型数据
    df1 = DataFrame(np.arange(12.).reshape((3, 4)), columns=list('abcd'))
    df2 = DataFrame(np.arange(20.).reshape((4, 5)), columns=list('abcde'))
    df3=df1.add(df2,fill_value=4)
    # 请在此添加代码 完成本关任务
    # ********** Begin *********#
 
 
    # ********** End **********#
 
    # 返回df3
    return df3

第7关:数据的基本操作------去重

任务描述

本关任务:根据编程要求,完成相关代码的编写。

相关知识

为了完成本关任务,你需要掌握:

python 复制代码
duplicated();
drop_duplicates()。
duplicated()

DataFrame 的 duplicated 方法返回一个布尔型 Series,表示各行是否是重复行。具体用法如下:

python 复制代码
In[1]: df = DataFrame({'k1':['one']*3 + ['two']*4, 'k2':[1,1,2,3,3,4,4]})
In[2]: df
Out[2]: 
    k1  k2
0  one   1
1  one   1
2  one   2
3  two   3
4  two   3
5  two   4
6  two   4
In[3]: df.duplicated()
Out[3]: 
0    False
1     True
2    False
3    False
4     True
5    False
6     True
dtype: bool
drop_duplicates()
drop_duplicates() 

用于去除重复的行数,具体用法如下:

python 复制代码
In[4]: df.drop_duplicates()
Out[4]: 
    k1  k2
0  one   1
2  one   2
3  two   3
5  two   4

编程要求

根据提示,在右侧编辑器 Begin-End 内补充代码:

去除 df1 中重复的行,并把结果保存到 df2 中。

测试说明

如果答案正确,则会输出 True。

开始你的任务吧,祝你成功!

示例代码如下:

python 复制代码
# -*- coding: utf-8 -*-
from pandas import Series,DataFrame
import  pandas as pd
 
def delete_duplicated():
    '''
    返回值:
    df2: 一个DataFrame类型数据
    '''
 
    # df1是DataFrame类型数据
    df1 = DataFrame({'k1': ['one'] * 3 + ['two'] * 4, 'k2': [1, 1, 2, 3, 3, 4, 4]})
    # 请在此添加代码 完成本关任务
    # ********** Begin *********#
    df2=df1.drop_duplicates()
 
    # ********** End **********#
 
    # 返回df2
    return df2

第8关:数据重塑

任务描述

本关任务:根据编程要求,完成相关代码的编写。

相关知识

为了完成本关任务,你需要掌握:

层次化索引;

索引方式;

内层选取;

数据重塑。

层次化索引

层次化索引(hierarchical indexing)是 pandas 的一项重要功能,它使我们能在一个轴上拥有多个(两个以上)索引级别。请看以下例子:

python 复制代码
In[1]:data = Series(np.random.randn(10), index = [['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'd', 'd' ],[1,2,3,1,2,3,1,2,2,3]])
In[2]:data
Out[2]:
a  1    0.169239
   2    0.689271
   3    0.879309
b  1   -0.699176
   2    0.260446
   3   -0.321751
c  1    0.893105
   2    0.757505
d  2   -1.223344
   3   -0.802812
dtype: float64

索引方式

python 复制代码
In[3]:data['b':'d']
Out[3]:
b  1   -0.699176
   2    0.260446
   3   -0.321751
c  1    0.893105
   2    0.757505
d  2   -1.223344
   3   -0.802812
dtype: float64

内层选取

python 复制代码
In[4]:data[:, 2]
Out[4]:
a    0.689271
b    0.260446
c    0.757505
d   -1.223344
dtype: float64

数据重塑

将 Series 转化成 DataFrame:

python 复制代码
in[5]:data.unstack()
Out[5]:
1                    2            3
a    0.169239    0.689271    0.879309
b    -0.699176   0.260446  -0.321751
c    0.893105    0.757505    NaN
d    NaN        -1.223344   -0.802812

编程要求

根据提示,在右侧编辑器 Begin-End 内补充代码:

对 s1 进行数据重塑,转化成 DataFrame 类型,并复制到 d1。

测试说明

编写代码之后,点击测评即可。

示例代码如下:

python 复制代码
# -*- coding: utf-8 -*-
from pandas import Series,DataFrame
import  pandas as pd
import numpy as np
def suoying():
    '''
    返回值:
    d1: 一个DataFrame类型数据
    '''
    #s1是Series类型数据
    s1=Series(np.random.randn(10),
           index=[['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'd', 'd'], [1, 2, 3, 1, 2, 3, 1, 2, 2, 3]])
    # 请在此添加代码 完成本关任务
    # ********** Begin *********#
    d1=s1.unstack()
 
    # ********** End **********#
 
    # 返回d1
    return d1

相关推荐
万粉变现经纪人8 分钟前
如何解决 pip install 代理报错 SOCKS5 握手失败 ReadTimeoutError 问题
java·python·pycharm·beautifulsoup·bug·pandas·pip
晨晨渝奇1 小时前
pandas 中将两个 DataFrame 分别导出到同一个 Excel 同一个工作表(sheet1)的 A1 单元格和 D1 单元格
excel·pandas
jarreyer2 天前
python,numpy,pandas和matplotlib版本对应关系
python·numpy·pandas
写代码的【黑咖啡】2 天前
Python中的Pandas:数据分析的利器
python·数据分析·pandas
对方正在长头发丿2 天前
Numpy学习篇
python·学习·jupyter·pycharm·numpy
狮子雨恋2 天前
Python 多维数组学习示例
python·学习·numpy
laocooon5238578864 天前
对传入的 x , y 两个数组做折线图, x 对应 x 轴, y 对应 y 轴。并保存到 Task1/image1/T2.png
python·numpy·pandas·matplotlib
中科院提名者5 天前
KNN实战进阶:模型评估、Scikit-learn实现与Numpy手动编码
python·numpy·scikit-learn
Maxwell_li15 天前
新冠检测例子学习查准率和召回率
学习·机器学习·数据分析·回归·numpy·pandas
渡我白衣5 天前
Python 与数据科学工具链入门:NumPy、Pandas、Matplotlib 快速上手
人工智能·python·机器学习·自然语言处理·numpy·pandas·matplotlib