Python 中列的绝对值

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

如何将“count”列的值转换为绝对值?

我的数据框摘要:

               datetime       count
0   2011-01-20 00:00:00   14.565996
1   2011-01-20 01:00:00   10.204177
2   2011-01-20 02:00:00   -1.261569
3   2011-01-20 03:00:00    1.938322
4   2011-01-20 04:00:00    1.938322
5   2011-01-20 05:00:00   -5.963259
6   2011-01-20 06:00:00   73.711525
python pandas dataframe calculated-columns absolute-value
2个回答
98
投票

使用

pandas.DataFrame.abs()

import pandas as pd

df = pd.DataFrame(data={'count':[1, -1, 2, -2, 3, -3]})

df['count'] = df['count'].abs()

print(df)
   count
#0      1
#1      1
#2      2
#3      2
#4      3
#5      3

0
投票

您也可以在多个列上调用

abs()

df[['col1', 'col2']] = df[['col1', 'col2']].abs()

或者也使用 numpy

abs()
,有趣的是它返回一个 pandas 对象,而不是 numpy 数组:

df['col1'] = np.abs(df['col1'])

顺便说一句,如果将列值转换为绝对值时得到

SettingWithCopyWarning
,则意味着您的数据框可能是通过过滤另一个数据框创建的。打开写时复制模式以将其关闭。请参阅这篇文章了解更多信息。

pd.options.mode.copy_on_write = True

df['count'] = df['count'].abs()

或使用

assign()
进行复印。

df = df.assign(count=df['count'].abs())
© www.soinside.com 2019 - 2024. All rights reserved.