如何将函数应用于 pandas 中的特定列

问题描述 投票:0回答:1

我有一个简单的问题。 我试图将函数应用于数据框中的 2 列,但收到错误消息。 我不知道我的代码做错了什么?

import pandas as pd
import numpy as np
data = [(3_000_000,5_000_000,7_000), 
        (2_000_000_000,4_000_000,6_000_000),
        (5_000_000,8_000_000,9_000_000)]
df = pd.DataFrame(data, columns = ['A','B','C'])


def human_format(num, round_to=1):
    magnitude = 0
    while abs(num) >= 1000:
        magnitude += 1
        num = round(num / 1000.0, round_to)
    return '{:.{}f}{}'.format(num, round_to, ['', 'K', 'M', 'B', 'G'][magnitude])

df[['A','B']] = df[['A','B']].apply(lambda x : human_format(x))
df

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我尝试过:

df['A'] = df['A'].apply(lambda x : human_format(x))
df['B'] = df['B'].apply(lambda x : human_format(x))

这有效。为什么?

我正在尝试将函数应用于数据框的 2 列,但收到错误消息。

python pandas dataframe apply
1个回答
0
投票

发生错误的原因是 pandas DataFrame 中的 apply() 函数一次对整行或整列进行操作,而不仅仅是一项。

如果要对多列中的每个项目使用函数,则应该使用 applymap(),如下所示:

df[['A','B']] = df[['A','B']].applymap(human_format)
© www.soinside.com 2019 - 2024. All rights reserved.