Small case: apply method of pandas

There is a particularly useful apply method in pandas, including

  • In-column calculations, only certain calculations are performed on a certain column
  • Calculations between columns, complex calculations between multiple columns
    Let's look at the experimental data

import pandas as pd
import numpy as np

matrix = [
['Zhang San', '1995-12-31','Shandong','Undergraduate'],
['Li Si', '1993-05-29','Hebei','College'],
[ 'Wang Wu', '1995-03-14','Shanxi','Master'],
['Zhao Liu', '1992-07-08','Inner Mongolia','Undergraduate'],
]

df = pd.DataFrame(matrix, columns=['Name', 'Birthday', 'From', 'Edu'])
df


![](https://s4.51cto.com/images/blog/202012/30/8732ee5fb5eaec5ebd93c4ea8631b1a4.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)
**df.apply(func)或series.apply(func)**
axis控制操作方向

* 0 表示列方向
* 1 表示行方向
**列内计算**
一般列内计算,实际上主要是对series做的操作,比如选中dataframe某列。

df['colname'].apply(func) 默认只对列方向对colname列做func操作,例如计算每个员工的出生年份、年龄。

def year(birthday):
#Intercept the year of the birthday string
return int(birthday[:4])

#Use the year function operation on the birthday column
df['Year'] = df['Birthday'].apply(year)

#
Agedf['Age'] = 2020-df['Year']

df


![](https://s4.51cto.com/images/blog/202012/30/4f41556903f7932897c29fb73d2378d9.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)
**列间计算**
df.apply(func, axis=1)不同列之间可以有复杂的计算,比如想计算 设计自我介绍模板

def intro(r):
#r refers to any row in the dataframe. It is series type data and has a dictionary-like usage method.
return'Hello everyone, I'm {name},\
from {province} province, \
this year {age} years old! '.format(name=r['Name'],
province=r['From'],
age=r['Age'])

df['Intro'] = df.apply(intro, axis=1)
df



![](https://s4.51cto.com/images/blog/202012/30/dc1af803e8cb6031a1c61af182f1a485.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)

Guess you like

Origin blog.51cto.com/15069487/2578567
Recommended