gpt4 book ai didi

python - 将数据框的所有数字列转换为绝对值

转载 作者:太空宇宙 更新时间:2023-11-03 13:38:11 24 4
gpt4 key购买 nike

我想将数据框中的所有数字列转换为它们的绝对值,并且正在这样做:

df = df.abs()

但是,它给出了错误:

*** TypeError: bad operand type for abs(): 'unicode'

如何解决这个问题?我真的希望不必手动指定列名

最佳答案

你可以使用 np.issubdtype使用 apply 检查列的 dtype 是否为 np.number。使用@Amy Tavory 示例:

df = pd.DataFrame({'a': ['-1', '2'], 'b': [-1, 2]})
res = df.apply(lambda x: x.abs() if np.issubdtype(x.dtype, np.number) else x)

In [14]: res
Out[14]:
a b
0 -1 1
1 2 2

或者您可以使用 np.dtype.kind检查您的 dtype 是否为数字:

res1 = df.apply(lambda x: x.abs() if x.dtype.kind in 'iufc' else x)


In [20]: res1
Out[20]:
a b
0 -1 1
1 2 2

注意:您可能还对 NumPy dtype hierarchy 感兴趣

关于python - 将数据框的所有数字列转换为绝对值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36272763/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com