【问题标题】:Check the datatype of Pandas Series & convert String to Number检查 Pandas 系列的数据类型并将字符串转换为数字
【发布时间】:2018-04-26 14:03:51
【问题描述】:

我有一个这样的系列(ts),我用一个替换了空值:

       Date
    2013-04-28             1
    2013-04-29             1
    2013-04-30             1
    2013-05-01             1
           ...    
    2018-03-11    6296370000
    2018-03-12    6457400000
    2018-03-13    5991140000

Name: Volume, Length: 1808, dtype: object

ts.dtype 给我:dtype('O')

如何检查Series的值是否为数字,如果是字符串,将其转换为数字/int?

提前谢谢

【问题讨论】:

  • 你可以使用isdigit()

标签: python pandas dataframe time-series


【解决方案1】:

使用apply

例如:

import pandas as pd
df = pd.DataFrame({"a": ["1","1","1","1", "a", "a"]})
print(df["a"].apply(lambda x: int(x) if x.isdigit() else x))

输出:

0    1
1    1
2    1
3    1
4    a
5    a
Name: a, dtype: object

【讨论】:

    【解决方案2】:

    使用to_numeric

    pd.to_numeric(df.a,errors='coerce').fillna(df.a)
    Out[204]: 
       a
    0  1
    1  1
    2  1
    3  1
    4  a
    5  a
    

    更多信息

    pd.to_numeric(df.a,errors='coerce').fillna(df.a).apply(type)
    Out[217]: 
    0    <class 'float'>
    1    <class 'float'>
    2    <class 'float'>
    3    <class 'float'>
    4      <class 'str'>
    5      <class 'str'>
    Name: a, dtype: object
    

    【讨论】:

      猜你喜欢
      • 2016-11-14
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多