将整个pandas数据帧转换为pandas中的整数(0.17.0)

Bob*_*ant 33 python pandas

我的问题与非常相似,但我需要转换整个数据帧而不仅仅是一系列.该to_numeric函数一次只能在一个系列上运行,并且不能替代已弃用的convert_objects命令.有没有办法convert_objects(convert_numeric=True)在新的pandas版本中获得与命令类似的结果?

谢谢MikeMüller的例子.df.apply(pd.to_numeric)如果值都可以转换为整数,则效果很好.如果在我的数据框中我有无法转换为整数的字符串怎么办?例:

df = pd.DataFrame({'ints': ['3', '5'], 'Words': ['Kobe', 'Bryant']})
df.dtypes
Out[59]: 
Words    object
ints     object
dtype: object
Run Code Online (Sandbox Code Playgroud)

然后我可以运行已弃用的函数并获取:

df = df.convert_objects(convert_numeric=True)
df.dtypes
Out[60]: 
Words    object
ints      int64
dtype: object
Run Code Online (Sandbox Code Playgroud)

运行该apply命令会给我带来错误,即使是尝试和处理也是如此.

Mik*_*ler 82

所有列都可以转换

您可以将该函数应用于所有列:

df.apply(pd.to_numeric)
Run Code Online (Sandbox Code Playgroud)

例:

>>> df = pd.DataFrame({'a': ['1', '2'], 
                       'b': ['45.8', '73.9'],
                       'c': [10.5, 3.7]})

>>> df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 2 entries, 0 to 1
Data columns (total 3 columns):
a    2 non-null object
b    2 non-null object
c    2 non-null float64
dtypes: float64(1), object(2)
memory usage: 64.0+ bytes

>>> df.apply(pd.to_numeric).info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 2 entries, 0 to 1
Data columns (total 3 columns):
a    2 non-null int64
b    2 non-null float64
c    2 non-null float64
dtypes: float64(2), int64(1)
memory usage: 64.0 bytes
Run Code Online (Sandbox Code Playgroud)

并非所有列都可以转换

pd.to_numeric有关键字参数errors:

  Signature: pd.to_numeric(arg, errors='raise')
  Docstring:
  Convert argument to a numeric type.

Parameters
----------
arg : list, tuple or array of objects, or Series
errors : {'ignore', 'raise', 'coerce'}, default 'raise'
    - If 'raise', then invalid parsing will raise an exception
    - If 'coerce', then invalid parsing will be set as NaN
    - If 'ignore', then invalid parsing will return the input
Run Code Online (Sandbox Code Playgroud)

ignore如果无法将其转换为数字类型,则将其设置为将更改列.

正如Anton Protopopov所指出的,最优雅的方式是提供ignore关键字参数apply():

>>> df = pd.DataFrame({'ints': ['3', '5'], 'Words': ['Kobe', 'Bryant']})
>>> df.apply(pd.to_numeric, errors='ignore').info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 2 entries, 0 to 1
Data columns (total 2 columns):
Words    2 non-null object
ints     2 non-null int64
dtypes: int64(1), object(1)
memory usage: 48.0+ bytes
Run Code Online (Sandbox Code Playgroud)

我以前建议的方法,使用模块中的partialfunctools,更详细:

>>> from functools import partial
>>> df = pd.DataFrame({'ints': ['3', '5'], 
                       'Words': ['Kobe', 'Bryant']})
>>> df.apply(partial(pd.to_numeric, errors='ignore')).info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 2 entries, 0 to 1
Data columns (total 2 columns):
Words    2 non-null object
ints     2 non-null int64
dtypes: int64(1), object(1)
memory usage: 48.0+ bytes
Run Code Online (Sandbox Code Playgroud)

  • 我认为,在`apply`中将这个参数设置为keywarg的最优雅方式是:`df.apply(pd.to_numeric,errors ='ignore')`应该可以正常工作. (6认同)

que*_*o42 5

pd.to_numeric() 接受的答案会在需要时立即转换为浮点数。详细阅读问题,它是将任何数字列转换为整数。这就是为什么接受的答案需要对所有列进行循环以最终将数字转换为 int 。

为了完整起见,这甚至可以在没有 pd.to_numeric(); 的情况下实现。当然,不建议这样做:

df = pd.DataFrame({'a': ['1', '2'], 
                   'b': ['45.8', '73.9'],
                   'c': [10.5, 3.7]})

for i in df.columns:
    try:
        df[[i]] = df[[i]].astype(float).astype(int)
    except:
        pass

print(df.dtypes)
Run Code Online (Sandbox Code Playgroud)

出去:

a    int32
b    int32
c    int32
dtype: object
Run Code Online (Sandbox Code Playgroud)

编辑: 请注意,这个不推荐的解决方案不必要地复杂;pd.to_numeric()可以简单地使用关键字参数downcast='integer'来强制整数作为输出,谢谢您的评论。不过,在接受的答案中仍然缺少这一点。

又是新闻从用户Gary 的评论中可以看出,“从 pandas 2.0.1 开始,如果输入系列包含空字符串,或者None即使使用时,结果 dtype 仍将是 float downcast='integer'”。这意味着.astype(float).astype(int)如果您想确保只获得整数,则第一个答案再次有效。

  • 如果所有“数字”都格式化为整数(即​​“5”,而不是“5.0”),则可以在“to_numeric”函数中使用关键字参数“downcast='integer”来强制整数类型:在此示例中 ```df.apply(pd.to_numeric, downcast='integer')``` 将返回列 `a` 作为整数 (2认同)