pandas DataFrame 根据多列的值做判断,生成新的列值实例
环境:Python3.6.4 + pandas 0.22
主要是DataFrame.apply函数的应用,如果设置axis参数为1则每次函数每次会取出DataFrame的一行来做处理,如果axis为1则每次取一列。
如代码所示,判断如果城市名中含有ing字段且年份为2016,则新列test值赋为1,否则为0.
import numpy as np import pandas as pd data = {'city': ['Beijing', 'Shanghai', 'Guangzhou', 'Shenzhen', 'Hangzhou', 'Chongqing'], 'year': [2016,2016,2015,2017,2016, 2016], 'population': [2100, 2300, 1000, 700, 500, 500]} frame = pd.DataFrame(data, columns = ['year', 'city', 'population', 'debt']) def function(a, b): if 'ing' in a and b == 2016: return 1 else: return 0 print(frame, '\n') frame['test'] = frame.apply(lambda x: function(x.city, x.year), axis = 1) print(frame)
运行结果如下:
另外Series类型也有apply函数,用法示例如下:
import numpy as np import pandas as pd data = {'city': ['Beijing', 'Shanghai', 'Guangzhou', 'Shenzhen', 'Hangzhou', 'Chongqing'], 'year': [2016,2016,2015,2017,2016, 2016], 'population': [2100, 2300, 1000, 700, 500, 500]} frame = pd.DataFrame(data, columns = ['year', 'city', 'population', 'debt']) print(frame, '\n') frame['panduan'] = frame.city.apply(lambda x: 1 if 'ing' in x else 0) print(frame)
运行结果如下:
相关推荐
roamer 2020-10-29
三石 2020-08-23
QianYanDai 2020-08-16
mmmjyjy 2020-07-16
QianYanDai 2020-07-05
QianYanDai 2020-07-05
jiahaohappy 2020-06-21
QianYanDai 2020-06-16
zhangxiaojiakele 2020-05-25
jzlixiao 2020-05-15
jiahaohappy 2020-05-12
zhangxiaojiakele 2020-05-11
jzlixiao 2020-05-08
Series是一种类似于一维数组的对象,由一组数据以及一组与之对应的索引组成。 index: 索引序列,必须是唯一的,且与数据的长度相同. 如果没有传入索引参数,则默认会自动创建一个从0~N的整数索引
jzlixiao 2020-05-09
81510295 2020-11-17
listep 2020-09-11
Tristahong 2020-08-24
Johnson0 2020-07-28
santiago00 2020-07-11