将函数应用于Pandas DataFrame中的每一行
通过将lambda函数应用于每一行
示例
import pandas as pd
df = pd.DataFrame([(10, 3, 13),(0, 42, 11),(26, 52, 1)], columns=list('xyz'))
print("Existing matrix")
print(df)
NewMatrix = df.apply(lambda a: a + 10, axis=1)
print("Modified Matrix")
print(NewMatrix)输出结果
运行上面的代码给我们以下结果-
Existing matrix
x y z
0 10 3 13
1 0 42 11
2 26 5 21
Modified Matrix
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("Existing matrix")
print(df)
NewMatrix = df.apply(SquareData, axis=1)
print("Modified Matrix")
print(NewMatrix)输出结果
运行上面的代码给我们以下结果-
Existing matrix
x y z
0 10 3 13
10 42 1 1
2 26 52 1
Modified Matrix
x y z
0 100 9 169
1 0 1764 121
2 676 2704 1热门推荐
10 分手毕业祝福语简短女生
11 最搞笑生日祝福语简短
12 周末祝福语正能量简短
13 潮汕生日谚语祝福语简短
14 叔叔生日祝福语简短励志
15 打牌翻盘祝福语简短
16 38节贺卡简短祝福语
17 班级集体生日祝福语简短
18 祖国生日祝福语简短英文