Pandas中常见的数据处理功能(reindexing, drop, selection, sorting, mapping/apply..等)

Pandas有Seriers和DataFrame两大数据结构, Seriers 处理一唯数据, 每个数据有一个对应指针index。DataFrame 处理二维数据,每个数据有一个对应的index和一个对应的column。

关于Seriers和DataFrame更详细的内容请参考:

对指针重新索引, 如果新定义的指针没有对应数据,会用NaN自动补足.

In [2]: obj = pd.Series([5.2, 2.1, -4.5, 2.65], index=['c', 'a', 'd', 'b'])

In [3]: obj
Out[3]:
c    5.20
a    2.10
d   -4.50
b    2.65
dtype: float64

In [6]: obj2 = obj.reindex(['a', 'b', 'c', 'd', 'f'])

In [7]: obj2
Out[7]:
a    2.10
b    2.65
c    5.20
d   -4.50
f     NaN
dtype: float64

可以分别按行 或 列 reindex

In [27]: frame = pd.DataFrame(np.random.randint(10, size=(3, 3)),
    ...:                      index=['d', 'b', 'a'],
    ...:                      columns=['three', 'four', 'one'])
    ...:

In [28]: frame
Out[28]:
   three  four  one
d      7     9    7
b      6     8    5
a      4     1    8

#default是按 行 reindex
In [29]: frame2 = frame.reindex(['a', 'b', 'c', 'd'])

In [30]: frame2
Out[30]:
   three  four  one
a    4.0   1.0  8.0
b    6.0   8.0  5.0
c    NaN   NaN  NaN
d    7.0   9.0  7.0

#指定按列 reindex
In [31]: frame3 = frame.reindex(columns=['one', 'two', 'three', 'four'])

In [32]: frame3
Out[32]:
   one  two  three  four
d    7  NaN      7     9
b    5  NaN      6     8
a    8  NaN      4     1

也可以用loc方法来reindex, 但是用loc方法 不会创造NaN数据出来。

In [33]: frame.loc[['a', 'b', 'd'], ['one', 'three', 'four']]
Out[33]:
   one  three  four
a    8      4     1
b    5      6     8
d    7      7     9

剔除某行某列数据, 这种方法默认会返回一个新的数据set.

In [34]: obj
Out[34]:
c    5.20
a    2.10
d   -4.50
b    2.65
dtype: float64

In [35]: obj.drop('a')
Out[35]:
c    5.20
d   -4.50
b    2.65
dtype: float64

In [36]: obj.drop(['a', 'c'])
Out[36]:
d   -4.50
b    2.65
dtype: float64
In [40]: frame
Out[40]:
   three  four  one
d      7     9    7
b      6     8    5
a      4     1    8

In [41]: frame.drop(['a', 'd'])
Out[41]:
   three  four  one
b      6     8    5

#通过指定axis =1 或者axis='columns'来drop列
In [42]: frame.drop('one', axis=1)
Out[42]:
   three  four
d      7     9
b      6     8
a      4     1

In [43]: frame.drop('one', axis='columns')
Out[43]:
   three  four
d      7     9
b      6     8
a      4     1

第一种方法: 通过类似于Numpy array的索引:

In [44]: obj
Out[44]:
c    5.20
a    2.10
d   -4.50
b    2.65
dtype: float64

In [45]: obj['a']
Out[45]: 2.1

In [46]: obj[1]
Out[46]: 2.1

In [47]: obj[2:4]
Out[47]:
d   -4.50
b    2.65
dtype: float64

In [48]: obj[['a', 'b']]
Out[48]:
a    2.10
b    2.65
dtype: float64

In [49]: obj[[1, 3]]
Out[49]:
a    2.10
b    2.65
dtype: float64

In [50]: obj[obj<0] out[50]: d -4.5 dtype: float64 < code></0]>

第二种方法: 通过loc/ iloc方法来索引。loc 是按index的名称来索引, iloc是按照index的所在位置来索引。

In [51]: obj.loc[['a', 'b']]
Out[51]:
a    2.10
b    2.65
dtype: float64

如果index是整数integer的话, 用loc索引或者用第一种方法[]索引, 会把这个整数当成index,如下。

In [55]: obj1 = pd.Series([1, 2, 3], index=[2, 0, 1])

In [59]: obj1[[0, 1, 2]]
Out[59]:
0    2
1    3
2    1
dtype: int64

In [60]: obj1.loc[[0, 1, 2]]
Out[60]:
0    2
1    3
2    1
dtype: int64

在这种情况下, 若想通过位置来索引的话, 需要用iloc方法。

In [61]: obj1.iloc[[0, 1, 2]]
Out[61]:
2    1
0    2
1    3
dtype: int64

注意:用第一种方法或者用loc方法时,如果index是整数,会把这个数当作索引指标, 这个时候就不能通过位置来索引了, 如:

In [67]: ser = pd.Series(np.arange(4))

In [68]: ser[-1]
KeyError: -1

这里的索引指标是按照ser的index 0, 1, 2, 3 来的, -1没有在这index里面所以会有keyerror. 如果index不是整数的话, 没有问题, 因为他会把传入的数字当成位置指引,而非index指引:

In [69]: ser1 = pd.Series(np.arange(4), index=['a', 'b', 'c', 'd'])

In [70]: ser1[-1]
Out[70]: 3

第一种方法:

In [62]: frame
Out[62]:
   three  four  one
d      7     9    7
b      6     8    5
a      4     1    8

In [63]: frame['three']
Out[63]:
d    7
b    6
a    4
Name: three, dtype: int64

In [64]: frame[['three', 'one']]
Out[64]:
   three  one
d      7    7
b      6    5
a      4    8

第二种方法:loc方法

In [65]: frame.loc['a', ['one', 'three']]
Out[65]:
one      8
three    4
Name: a, dtype: int64

In [66]: frame.iloc[2, [2, 0]]
Out[66]:
one      8
three    4
Name: a, dtype: int64
In [82]: frame
Out[82]:
   three  four  one
d      7     9    7
b      6     8    5
a      4     1    8

In [83]: f = lambda x: x.max() + x.min()

&#x6309;&#x884C;
In [84]: frame.apply(f)
Out[84]:
three    11
four     10
one      13
dtype: int64

&#x6309;&#x5217;
In [85]: frame.apply(f, axis='columns')
Out[85]:
d    16
b    13
a     9
dtype: int64

如果是element-wise 运算的话需要用applymap 而非apply

In [82]: frame
Out[82]:
   three  four  one
d      7     9    7
b      6     8    5
a      4     1    8

In [89]: f1 = lambda x: x+ 10

In [90]: frame.applymap(f1)
Out[90]:
   three  four  one
d     17    19   17
b     16    18   15
a     14    11   18

按照某个指标排序, 比如指标排序, 或按内容排序。

In [91]: obj
Out[91]:
c    5.20
a    2.10
d   -4.50
b    2.65
dtype: float64

&#x6309;&#x6307;&#x9488;&#x6392;&#x5E8F;
In [92]: obj.sort_index()
Out[92]:
a    2.10
b    2.65
c    5.20
d   -4.50
dtype: float64

&#x6309;&#x5185;&#x5BB9;&#x6392;&#x5E8F;
In [93]: obj.sort_values()
Out[93]:
d   -4.50
a    2.10
b    2.65
c    5.20
dtype: float64
In [94]: frame
Out[94]:
   three  four  one
d      7     9    7
b      6     8    5
a      4     1    8

&#x6309;&#x884C;index&#x6392;&#x5E8F;
In [95]: frame.sort_index()
Out[95]:
   three  four  one
a      4     1    8
b      6     8    5
d      7     9    7

&#x6309;&#x5217;index&#x6392;&#x5E8F;
In [96]: frame.sort_index(axis=1)
Out[96]:
   four  one  three
d     9    7      7
b     8    5      6
a     1    8      4

&#x6309;&#x964D;&#x5E8F;&#x6392;&#x5E8F;
In [97]: frame.sort_index(axis=1, ascending=False)
Out[97]:
   three  one  four
d      7    7     9
b      6    5     8
a      4    8     1

&#x6309;&#x6307;&#x5B9A;&#x5217;&#x7684;&#x5185;&#x5BB9;&#x6392;&#x5E8F;
In [99]: frame.sort_values(by='one')
Out[99]:
   three  four  one
b      6     8    5
d      7     9    7
a      4     1    8

参考自: Python for Data Analysis, 2nd Edition by Wes McKinney

Original: https://blog.csdn.net/bo17244504/article/details/124732529
Author: amateur
Title: Pandas中常见的数据处理功能(reindexing, drop, selection, sorting, mapping/apply..等)

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/753645/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • pandas基础

    目录 文件读取: 数据结构: seriers: dataframe: 常用基本函数: 汇总函数: 唯一值函数: 排序函数: 文件读取: pandas可以简单的读取csv,excel…

    Python 2023年8月8日
    062
  • 如何用python制作动画电影_如何用pygam制作动画

    对于动画,你需要一堆图像和一个计时器。在 我将展示一些基于pygame精灵的代码片段。也许这并不完全符合这个问题,但它似乎是一个比手动绘制/blitting图像更好的解决方案。在 …

    Python 2023年9月22日
    034
  • C++中调用matplotlibcpp.h画图测试笔记

    一、相关的程序码仓地址 Matplotlib 是一个 Python 的 2D绘图库,它以各种硬拷贝格式和跨平台的交互式环境生成出版质量级别的图形。 相关参考资料Matplotlib…

    Python 2023年9月5日
    038
  • python numpy

    NumPyndarray对象 NumPy 最重要的一个特点是其 N 维数组对象 ndarray,它是一系列同类型数据的集合,以 0 下标为开始进行集合中元素的索引。 import …

    Python 2023年8月27日
    047
  • 异构图神经网络 RGCN、RGAT、HAN、GNN-FILM + PyG实现

    背景 ICDM 2022 : 大规模电商图上的风险商品检测,要求在一张异构图上跑点分类,由于是异常检测,正负样本数据集在1比10,记录一下初赛过程。 数据 ; 过程 赛事官方开源了…

    Python 2023年9月30日
    040
  • python bar图 百分比_如何将条形图值更改为百分比(Matplotlib)

    下面的代码生成一个条形图,每个条形图上方都有数据标签(如下图所示)。有没有办法把y轴上的刻度变成百分比(在这个图表中,是0%,20%,等等)? 我通过将条高与”%&#8…

    Python 2023年8月8日
    062
  • Python实现人脸识别功能,face_recognition的使用 | 机器学习

    前言 接着上一篇:AI识别照片是谁,人脸识别face_recognition开源项目安装使用 | 机器学习_阿良的博客-CSDN博客 根据项目提供的demo代码,调整了一下功能,自…

    Python 2023年10月26日
    055
  • 什么是网络爬虫?

    什么是网络爬虫 网络爬虫是一种在 Internet 上运行自动化任务的软件应用程序。与人类互联网活动相比,网络爬虫运行的任务通常很简单,并且执行速度要快得多。 有些机器人是合法的—…

    Python 2023年6月10日
    083
  • Python—数据分析与可视化编程

    目标: 掌握numpy模块基本操作;掌握matplotlib模块基础操作;掌握pandas模块基础操作。 内容: 1.编写程序,利用pyplot将绘图区域划分成2*1个子绘图区域,…

    Python 2023年8月6日
    076
  • MySQL锁,锁的到底是什么?

    MySQL锁系列文章已经鸽了挺久了,最近赶紧挤了挤时间,和大家聊一聊MySQL的锁。 只要学计算机,「 &#x9501;」永远是一个绕不过的话题。MySQL锁也是一样。 一…

    Python 2023年10月13日
    032
  • 重温Python基础,都是最基础的知识点

    前言 最近有很多朋友刚接触python学的还是有点模糊 还有的朋友就是想重温一下基础内容,毕竟基础不牢地动山摇 行吧,就总结了以下的一些知识点,可以都看看哈 ; 一、开发环境搭建 …

    Python 2023年8月1日
    054
  • pythonifelif按数字大小排列_python,if/elif/else语法按注释拆分?

    我在pygame中编写了这个函数作为滚动面板的一部分。该函数是名为slot的类的一部分,slot是panel类的一部分,slot是面板上包含字符串或数据的条。此方法将插槽绘制到屏幕…

    Python 2023年9月24日
    033
  • pytest零基础入门到精通(04)conftest文件详解

    conftest的作用 首先, conftest.py 的文件名称是固定的, pytest 会自动识别该文件,我们可以理解成一个专门存放 fixture 的配置文件。 一个工程下可…

    Python 2023年9月10日
    043
  • kubernetes数据持久化StorageClass动态供给(二)

    存储类的好处之一便是支持PV的动态供给,它甚至可以直接被视作为PV的创建模版,用户用到持久性存储时,需要通过创建PVC来绑定匹配的PV,此类操作需求较大,或者当管理员手动创建的PV…

    Python 2023年10月14日
    046
  • pytest中实用但不常用方法列举

    hello,大家好,今天和大家一起学习下pytest中实用但不常用的一些方法,作为一名测试,可能不像开发那样天天写代码,所以有时我们会逐渐遗忘一些方法或这语法,所以以免后期我也遗忘…

    Python 2023年9月14日
    051
  • Python爬虫项目实战:快手网页版滑块captchaSession分析

    Original: https://www.cnblogs.com/pythonQqun200160592/p/15479685.htmlAuthor: python可乐编程Tit…

    Python 2023年5月25日
    049
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球