如何在 Pandas 中为单一列使用 apply() 函数?
我们可以使用 lambda 表达式对 DataFrame 的一列使用 apply() 函数。
步骤
创建一个可能存在不同的二维表格数据 df。
打印输入 DataFrame df。
使用 apply() 方法用 lambda x: x*2 表达式替换列 x。
打印修改后的 DataFrame。
示例
import pandas as pd
df = pd.DataFrame(
{
"x": [5, 2, 1, 5],
"y": [4, 10, 5, 10],
"z": [1, 1, 5, 1]
}
)
print "Input DataFrame is:
", df
df['x'] = df['x'].apply(lambda x: x * 2)
print "After applying multiplication of 2 DataFrame is:
", df输出
Input DataFrame is: x y z 0 5 4 1 1 2 10 1 2 1 5 5 3 5 10 1 After applying multiplication of 2 DataFrame is: x y z 0 10 4 1 1 4 10 1 2 2 5 5 3 10 10 1
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP