我想将数据框中的所有数字列转换为它们的绝对值,并且正在执行以下操作:
df = df.abs()
Run Code Online (Sandbox Code Playgroud)
但是,它给出了错误:
*** TypeError: bad operand type for abs(): 'unicode'
Run Code Online (Sandbox Code Playgroud)
如何解决这个问题?我真的不想手动指定列名
你可以使用np.issubdtype检查你列的D型是np.number或不是apply。使用@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
Run Code Online (Sandbox Code Playgroud)
或者你可以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
Run Code Online (Sandbox Code Playgroud)
注意:您可能还对NumPy dtype 层次结构感兴趣
比现有答案更快,而且更切题:
df.update(df.select_dtypes(include=[np.number]).abs())
Run Code Online (Sandbox Code Playgroud)
(小心:我注意到,当有一个不平凡的多重索引update时,有时不会做任何事情。一旦我弄清楚问题出在哪里,我就会更新这个答案。这对于平凡的范围索引来说绝对有效)df
借用这个问题的答案,选择数字列怎么样?
假设你从
df = pd.DataFrame({'a': ['-1', '2'], 'b': [-1, 2]})
>>> df
a b
0 -1 -1
1 2 2
Run Code Online (Sandbox Code Playgroud)
然后就做
numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
for c in [c for c in df.columns if df[c].dtype in numerics]:
df[c] = df[c].abs()
>>> df
a b
0 -1 1
1 2 2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5391 次 |
| 最近记录: |