如何在 Pandas 中对单列使用 apply() 函数?

pandasserver side programmingprogramming

我们可以使用 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 "输入 DataFrame 为:
", df df['x'] = df['x'].apply(lambda x: x * 2) print "进行 2 乘法运算后,DataFrame 为::
", df

输出

输入 DataFrame 为:
   x  y  z
0  5  4  1
1  2 10  1
2  1  5  5
3  5 10  1

进行 2 乘法运算后,DataFrame 为:
    x  y   z
0  10  4   1
1   4 10   1
2   2  5   5
3  10 10   1

相关文章