One - One Code All

Blog Content

基于Pandas的DataFrame、Series对象的apply方法

Python 统计学-科学计算   2016-02-14 22:11:14

frame.apply(lambda x: function(x.column), axis = 1)


主要是DataFrame.apply函数的应用,

数据类型为整型,默认为0。当axis=0时,会将DataFrame中的每一列抽出来做聚合运算,当axis=1时,会将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)


# eg
def foo(x, y, z):
    if z > 0.5:
        return x + y
    else:
        return x

d['fun'] = d.apply(lambda x: foo(x[0], x[2], x[4]), axis=1)



上一篇:python将dataframe转为字典
下一篇:pandas十分钟快速入门

The minute you think of giving up, think of the reason why you held on so long.