[Python] DataFrame uses apply() to implement multiple functional examples

*This article is an example of my own data analysis, please do not reprint without permission

1. Implement symbol/character replacement

import pandas as pd
import numpy as np
#将指定列的符号/字符进行替换
df['value'] = df['value'].apply(lambda x:x.replace(',','.'))
#input:3,10
#output:3.10

#将全文的符号/字符进行替换
st = st.apply(lambda x:x.replace('-',np.nan))
#input:'-'
#output:nan

2. Compare the values ​​of different columns and generate new columns

#如果一列的数据大于另外一列,则新列的值为1,反之为0
df_st['>ad hoc MTR'] = df_st.apply(lambda x:1 if x['value'] > x['ad hoc MTR'] else 0,axis=1)
df_st['>MTR'] = df_st.apply(lambda x:1 if x['value'] > x['MTR'] else 0,axis=1)
df_st['>JG-MKN'] = df_st.apply(lambda x:1 if x['value'] > x['JG-MKN'] else 0,axis=1)
df_st['>MAC-MKN'] = df_st.apply(lambda x:1 if x['value'] > x['MAC-MKN'] else 0,axis=1)
df_st['>toelatingscrit. Ctgb'] = df_st.apply(lambda x:1 if x['value'] > x['toelatingscrit. Ctgb'] else 0,axis=1)
df_st['>wettelijk'] = df_st.apply(lambda x:1 if x['value'] > x['wettelijk'] else 0,axis=1)
#将以上的数值进行求和
df_st['num_standard_exceed'] = df_st.apply(lambda x:sum(x['>ad hoc MTR':]),axis=1)

3. Extract data using regular expressions

import pandas as pd
import re
 
#创建DataFrame
df1 = pd.DataFrame([['2015-03-24'],['2011-07-12'],['2010-02-08']])
 
#使用apply()和lambda进行提取:月份
df1 = df1[0].apply(lambda x:re.findall('\d+-(\d+)-\d+',x)[0])

Guess you like

Origin blog.csdn.net/Father_of_Python/article/details/123260934