资讯详情

爱了爱了,20个好用到爆的Python函数

大家好,今天分享20份日常工作是必不可少的Python函数,这些函数平时看得不多,但是使用起来很方便,可以大大提高工作效率。

isin()方法

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

df =  pd.DataFrame(np.array(([1,  2,  3],  [4,  5,  6],  [7,  8,  9],  [10,  11,  12])),                                    index=['A',  'B',  'C',  'D'],                                    columns=['one',  'two',  'three'])df.isin([3,  5,  12])

output

          one    two  threeA  False    False      TrueB  False      True    FalseC  False    False    FalseD  False    False      True

如果列表中包含了数值,即3、5、12,则返回True,否则就返回False

df.plot.area()方法

让我们怎么做。Pandas图表是通过一行代码绘制的,所有列都是通过面积图绘制的

df =  pd.DataFrame({             'sales':  [30,  20,  38,  95,  106, 65],    'signups': [7, 9, 6, 12, 18, 13],    'visits': [20, 42, 28, 62, 81, 50],}, index=pd.date_range(start='2021/01/01', end='2021/07/01', freq='M'))ax = df.plot.area(figsize = (10, 5))

output

图片

df.plot.bar()方法

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

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

output

图片

当然我们也可以根据不同的类别来绘制柱状图

age = [0.1, 17.5, 40, 48, 52, 69, 88]weight = [2, 8, 70, 1.5, 25, 12, 28]index = ['A', 'B', 'C', 'D', 'E', 'F', 'G']df = pd.DataFrame({
     'age': age, 'weight': weight}, index=index)ax = df.plot.bar(rot=0)

output

图片

当然我们也可以横向来绘制图表

ax = df.plot.barh(rot=0)

output

图片

df.plot.box()方法

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

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

output

图片

df.plot.pie()方法

接下来是饼图的绘制

df = pd.DataFrame({
     'mass': [1.33, 4.87 , 5.97],                   'radius': [2439.7, 6051.8, 6378.1]},                  index=['Mercury', 'Venus', 'Earth'])plot = df.plot.pie(y='mass', figsize=(8, 8))

output

图片

除此之外,还有折线图、直方图、散点图等等,步骤与方式都与上述的技巧有异曲同工之妙,大家感兴趣的可以自己另外去尝试。

items()方法

pandas当中的items()方法可以用来遍历数据集当中的每一列,同时返回列名以及每一列当中的内容,通过以元组的形式,示例如下

df = pd.DataFrame({
     'species': ['bear', 'bear', 'marsupial'],                  'population': [1864, 22000, 80000]},                  index=['panda', 'polar', 'koala'])df

output

         species  populationpanda       bear        1864polar       bear       22000koala  marsupial       80000

然后我们使用items()方法

for label, content in df.items():    print(f'label: {
       label}')    print(f'content: {
       content}', sep='\n')    print("=" * 50)

output

label: speciescontent: panda         bearpolar         bearkoala    marsupialName: species, dtype: object==================================================label: populationcontent: panda     1864polar    22000koala    80000Name: population, dtype: int64==================================================

相继的打印出了‘species’和‘population’这两列的列名和相应的内容

iterrows()方法

而对于iterrows()方法而言,其功能则是遍历数据集当中的每一行,返回每一行的索引以及带有列名的每一行的内容,示例如下

for label, content in df.iterrows():    print(f'label: {
       label}')    print(f'content: {
       content}', sep='\n')    print("=" * 50)

output

label: pandacontent: species       bearpopulation    1864Name: panda, dtype: object==================================================label: polarcontent: species        bearpopulation    22000Name: polar, dtype: object==================================================label: koalacontent: species       marsupialpopulation        80000Name: koala, dtype: object==================================================

insert()方法

insert()方法主要是用于在数据集当中的特定位置处插入数据,示例如下

df.insert(1, "size", [2000, 3000, 4000])

output

         species  size  populationpanda       bear  2000        1864polar       bear  3000       22000koala  marsupial  4000       80000

可见在DataFrame数据集当中,列的索引也是从0开始的

assign()方法

assign()方法可以用来在数据集当中添加新的列,示例如下

df.assign(size_1=lambda x: x.population * 9 / 5 + 32)

output

         species  population    size_1panda       bear        1864    3387.2polar       bear       22000   39632.0koala  marsupial       80000  144032.0

从上面的例子中可以看出,我们通过一个lambda匿名函数,在数据集当中添加一个新的列,命名为‘size_1’,当然我们也可以通过assign()方法来创建不止一个列

df.assign(size_1 = lambda x: x.population * 9 / 5 + 32,          size_2 = lambda x: x.population * 8 / 5 + 10)

output

         species  population    size_1    size_2panda       bear        1864    3387.2    2992.4polar       bear       22000   39632.0   35210.0koala  marsupial       80000  144032.0  128010.0

eval()方法

eval()方法主要是用来执行用字符串来表示的运算过程的,例如

df.eval("size_3 = size_1 + size_2")

output

         species  population    size_1    size_2    size_3panda       bear        1864    3387.2    2992.4    6379.6polar       bear       22000   39632.0   35210.0   74842.0koala  marsupial       80000  144032.0  128010.0  272042.0

当然我们也可以同时对执行多个运算过程

df = df.eval('''size_3 = size_1 + size_2size_4 = size_1 - size_2''')

output

         species  population    size_1    size_2    size_3   size_4panda       bear        1864    3387.2    2992.4    6379.6    394.8polar       bear       22000   39632.0   35210.0   74842.0   4422.0koala  marsupial       80000  144032.0  128010.0  272042.0  16022.0

pop()方法

pop()方法主要是用来删除掉数据集中特定的某一列数据

df.pop("size_3")

output

panda      6379.6polar     74842.0koala    272042.0Name: size_3, dtype: float64

而原先的数据集当中就没有这个‘size_3’这一例的数据了

truncate()方法

truncate()方法主要是根据行索引来筛选指定行的数据的,示例如下

df = pd.DataFrame({
     'A': ['a', 'b', 'c', 'd', 'e'],                   'B': ['f', 'g', 'h', 'i', 'j'],                   'C': ['k', 'l', 'm', 'n', 'o']},                  index=[1, 2, 3, 4, 5])

output

   A  B  C1  a  f  k2  b  g  l3  c  h  m4  d  i  n5  e  j  o

我们使用truncate()方法来做一下尝试

df.truncate(before=2, after=4)

output

   A  B  C2  b  g  l3  c  h  m4  d  i  n

我们看到参数beforeafter存在于truncate()方法中,目的就是把行索引2之前和行索引4之后的数据排除在外,筛选出剩余的数据

count()方法

count()方法主要是用来计算某一列当中非空值的个数,示例如下

df = pd.DataFrame({
     "Name": ["John", "Myla", "Lewis", "John", "John"],                   "Age": [24., np.nan, 25, 33, 26],                   "Single": [True, True, np.nan, True, False]})

output

    Name   Age Single0   John  24.0   True1   Myla   NaN   True2  Lewis  25.0    NaN3   John  33.0   True4   John  26.0  False

我们使用count()方法来计算一下数据集当中非空值的个数

df.count()

output

Name      5Age       4Single    4dtype: int64

add_prefix()方法/add_suffix()方法

add_prefix()方法和add_suffix()方法分别会给列名以及行索引添加后缀和前缀,对于Series()数据集而言,前缀与后缀是添加在行索引处,而对于DataFrame()数据集而言,前缀与后缀是添加在列索引处,示例如下

s = pd.Series([1, 2, 3, 4])

output

0    11    22    33    4dtype: int64

我们使用add_prefix()方法与add_suffix()方法在Series()数据集上

s.add_prefix('row_')

output

row_0    1row_1    2row_2    3row_3    4dtype: int64

又例如

s.add_suffix('_row')

output

0_row    11_row    22_row    33_row    4dtype: int64

而对于DataFrame()形式数据集而言,add_prefix()方法以及add_suffix()方法是将前缀与后缀添加在列索引处的

df = pd.DataFrame({
     'A': [1, 2, 3, 4], 'B': [3, 4, 5, 6]})

output

   A  B0  1  31  2  42  3  53  4  6

示例如下

df.add_prefix("column_")

output

   column_A  column_B0         1         31         2         42         3         53         4         6

又例如

df.add_suffix("_column")

output

   A_column  B_column0         1         31         2         42         3         53         4         6

clip()方法

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

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

output

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

output

   col_0  col_10      4     -21     -3     -42      0      43     -1      44      4     -4

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

filter()方法

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

df = pd.DataFrame(np.array(([1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12])),                  index=['A', 'B', 'C', 'D'],                  columns=['one', 'two', 'three'])

output

   one  two  threeA    1    2      3B    4    5      6C    7    8      9D   10   11     12

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

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

output

   one  threeA    1      3B    4      6C    7      9D   10     12

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

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

output

   one  threeA    1      3B    4      6C    7      9D   10     12

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

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

output

   one  two  threeB    4    5      6

first()方法

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

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

output

            A2021-11-11  12021-11-13  22021-11-15  32021-11-17  42021-11-19  5

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

ts.first('3D')

output

            A2021-11-11  12021-11-13  2

技术交流

欢迎转载、收藏、有所收获点赞支持一下!

在这里插入图片描述

目前开通了技术交流群,群友已超过,添加时最好的备注方式为:来源+兴趣方向,方便找到志同道合的朋友

  • 方式①、发送如下图片至微信,长按识别,后台回复:加群;
  • 方式②、添加微信号:,备注:来自CSDN
  • 方式③、微信搜索公众号:,后台回复:加群

长按关注

标签: 涤纶myla电容

锐单商城拥有海量元器件数据手册IC替代型号,打造 电子元器件IC百科大全!

 锐单商城 - 一站式电子元器件采购平台  

 深圳锐单电子有限公司