将函数应用于Pandas DataFrame中的每一行
通过对每一行应用lambda函数实现
示例
import pandas as pd
df = pd.DataFrame([(10, 3, 13),(0, 42, 11),(26, 52, 1)], columns=list('xyz'))
print("原始矩阵")
print(df)
NewMatrix = df.apply(lambda a: a + 10, axis=1)
print("修改后的矩阵")
print(NewMatrix)
输出
运行以上代码将得到以下结果−
原始矩阵
x y z
0 10 3 13
1 0 42 11
2 26 5 21
修改后的矩阵
x y z
0 20 13 23
1 10 52 21
2 36 62 11
通过应用用户定义的函数
示例
import pandas as pd
def SquareData(x):
return x * x
df = pd.DataFrame([(10, 3, 13), (0, 42, 11), (26, 52, 1)], columns=list('xyz'))
print("原始矩阵")
print(df)
NewMatrix = df.apply(SquareData, axis=1)
print("修改后的矩阵")
print(NewMatrix)
输出
运行以上代码将得到以下结果−
原始矩阵
x y z
0 10 3 13
10 42 1 1
2 26 52 1
修改后的矩阵
x y z
0 100 9 169
1 0 1764 121
2 676 2704 1