Dataframe 根据其他列的条件新增一列
如代码所示,判断如果城市名中含有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)
你的时间用在哪里决定你成为一个什么样的人。