气泡水 发表于 2021-12-21 16:21:33

20 个好用的 pandas 函数!(下)

本帖最后由 气泡水 于 2021-12-21 16:29 编辑

  11、clip()方法

  clip()方法主要是通过设置阈值来改变数据集当中的数值,当数值超过阈值的时候,就做出相应的调整

data = {'col_0': , 'col_1': [-2, -7, 6, 8, -5]}
df = pd.DataFrame(data)

  output

df.clip(lower = -4, upper = 4)

  output

   col_0col_1
0      4   -2
1   -3   -4
2      0      4
3   -1      4
4      4   -4

  我们看到参数lower和upper分别代表阈值的上限与下限,数据集当中超过上限与下限的值会被替代。

  12、filter()方法

  pandas当中的filter()方法是用来筛选出特定范围的数据的,示例如下

df = pd.DataFrame(np.array((, , , )),
                  index=['A', 'B', 'C', 'D'],
                  columns=['one', 'two', 'three'])

  output

   onetwothree
A    1    2      3
B    4    5      6
C    7    8      9
D   10   11   12

  我们使用filter()方法来筛选数据

df.filter(items=['one', 'three'])

  output

   onethree
A    1      3
B    4      6
C    7      9
D   10   12

  我们还可以使用正则表达式来筛选数据

df.filter(regex='e$', axis=1)

  output

   onethree
A    1      3
B    4      6
C    7      9
D   10   12

  当然通过参数axis来调整筛选行方向或者是列方向的数据

df.filter(like='B', axis=0)

  output

   onetwothree
B    4    5      6

  13、first()方法

  当数据集当中的行索引是日期的时候,可以通过该方法来筛选前面几行的数据

index_1 = pd.date_range('2021-11-11', periods=5, freq='2D')
ts = pd.DataFrame({'A': }, index=index_1)
ts

  output

            A
2021-11-111
2021-11-132
2021-11-153
2021-11-174
2021-11-195

  我们使用first()方法来进行一些操作,例如筛选出前面3天的数据

ts.first('3D')

  output

            A
2021-11-111
2021-11-132

  14、isin()方法

  isin()方法主要是用来确认数据集当中的数值是否被包含在给定的列表当中

df = pd.DataFrame(np.array((, , , )),
                  index=['A', 'B', 'C', 'D'],
                  columns=['one', 'two', 'three'])
df.isin()

  output

   one    twothree
AFalseFalse   True
BFalse   TrueFalse
CFalseFalseFalse
DFalseFalse   True

       若是数值被包含在列表当中了,也就是3、5、12当中,返回的是True,否则就返回False

  15、df.plot.area()方法

  下面我们来讲一下如何在Pandas当中通过一行代码来绘制图表,将所有的列都通过面积图的方式来绘制

df = pd.DataFrame({
    'sales': ,
    'signups': ,
    'visits': ,
}, index=pd.date_range(start='2021/01/01', end='2021/07/01', freq='M'))

ax = df.plot.area(figsize = (10, 5))

  output



  16、df.plot.bar()方法

  下面我们看一下如何通过一行代码来绘制柱状图

df = pd.DataFrame({'label':['A', 'B', 'C', 'D'], 'values':})
ax = df.plot.bar(x='label', y='values', rot=20)

  output



  17、df.plot.box()方法

  我们来看一下箱型图的具体的绘制,通过pandas一行代码来实现

data = np.random.randn(25, 3)
df = pd.DataFrame(data, columns=list('ABC'))
ax = df.plot.box()

  output



  18、df.plot.pie()方法

  接下来是饼图的绘制
df = pd.DataFrame({'mass': ,
                   'radius': },
                  index=['Mercury', 'Venus', 'Earth'])
plot = df.plot.pie(y='mass', figsize=(8, 8))

         output



  【免责声明】本文系转载,来源于关于数据分析与可视化 ,作者俊欣 。转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责。如涉及作品内容、版权和其它问题,请在30日内与联系我们,我们会予以更改或删除相关文章,以保证您的权益!
页: [1]
查看完整版本: 20 个好用的 pandas 函数!(下)