如何对 Pandas 中的单个列使用 apply() 函数?
我们可以使用apply()lambda表达式在DataFrame的列上使用函数。
步骤
创建二维、大小可变、潜在异构的表格数据df。
打印输入数据帧,df。
使用方法用lambdax:x*2表达式覆盖列xapply()。
打印修改后的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:\n", df
df['x'] = df['x'].apply(lambda x: x * 2)
print "After applying multiplication of 2 DataFrame is:\n", 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