【问题标题】:How to turn a series of strings from a pandas column into integers如何将熊猫列中的一系列字符串转换为整数
【发布时间】:2023-04-07 16:41:01
【问题描述】:

我有一个 Pandas 数据框,其中包含日期列,格式为“2016-05-03”,顺便说一句,这些是字符串。我需要将它们从字符串转换为 int 并在连字符('-')处拆分,并且只提取年份 [0]。

这是我尝试将字符串转换为整数的方法:

tyc.startDate = tyc.startDate.astype(np.int64) 

但它正在返回和错误:

ValueError: int() 以 10 为底的无效文字:'2015-06-01'

这就是我为拆分所做的:

tyc.startDate.str.split('-')[0]

tyc.startDate.str.split('-', [0]) 

但这也不起作用,它以这种形式拆分并返回列中所有行的列表: ['2015', '06', '01'] 我只想分开一年!

我确信有一种简单的方法可以转换为 int 并在位置 0 处为 ('-') 拆分,然后将其作为新列放入 df,请帮助!

【问题讨论】:

    标签: python pandas split int


    【解决方案1】:

    我相信您的数据包含NaNs 或一些非日期时间值:

    tyc = pd.DataFrame({'startDate':['2016-05-03','2017-05-03', np.nan],
                        'col':[1,2,3]})
    print (tyc)
       col   startDate
    0    1  2016-05-03
    1    2  2017-05-03
    2    3         NaN
    

    使用str[0] 首先返回每行的第一个列表值。但是有问题 - 一些NaNs,不能转换为int(设计) - 所以输出是浮点数:

    print (tyc.startDate.str.split('-').str[0].astype(float))
    0    2016.0
    1    2017.0
    2       NaN
    Name: startDate, dtype: float64
    

    另一种解决方案是通过to_datetime 转换为日期时间并通过year 解析年份:

    print (pd.to_datetime(tyc.startDate, errors='coerce'))
    0   2016-05-03
    1   2017-05-03
    2          NaT
    Name: startDate, dtype: datetime64[ns]
    
    print (pd.to_datetime(tyc.startDate, errors='coerce').dt.year)
    0    2016.0
    1    2017.0
    2       NaN
    Name: startDate, dtype: float64
    

    删除NaNs的解决方案:

    tyc['year'] = pd.to_datetime(tyc.startDate, errors='coerce').dt.year
    print (tyc)
       col   startDate    year
    0    1  2016-05-03  2016.0
    1    2  2017-05-03  2017.0
    2    3         NaN     NaN
    

    1.

    通过dropna删除所有带有NaNs的行,然后转换为int:

    tyc = tyc.dropna(subset=['year'])
    tyc['year'] = tyc['year'].astype(int)
    print (tyc)
       col   startDate  year
    0    1  2016-05-03  2016
    1    2  2017-05-03  2017
    

    2.

    NaNs 替换为一些 int 值,例如 1fillna,然后转换为 int

    tyc['year'] = tyc['year'].fillna(1).astype(int)
    print (tyc)
       col   startDate  year
    0    1  2016-05-03  2016
    1    2  2017-05-03  2017
    2    3         NaN     1
    

    【讨论】:

    • 嗯,你在 cmets 中写了另一个解决方案的一些问题,所以另一个解决方案工作得很好,所以被接受了吗?还是不行?
    • 有问题只能接受一种解决方案 - 所以您必须在我的解决方案或其他解决方案之间做出选择。不可能同时接受。
    【解决方案2】:

    你可以使用apply:

    def mod_strings(date_str):
        try:
            return int(date_str.split('-')[0])
        except (AttributeError, IndexError):  # in case value is not as 
                                              # expected returning original value
            return date_str
    
    tyc.startDate = tyc.startDate.apply(mod_strings)
    

    但将整个列从字符串转换为日期对象然后使用tyc.startDate = tyc.startDate.dt.year(假设 pandas 版本 >= 0.16)可能更容易

    【讨论】:

    • 嘿@DeepSpace!谢谢你。我已经尝试过了,但出现了这个错误:AttributeError: 'float' object has no attribute 'split'
    • @s.23 显然,有些行包含一个浮点对象,而不是startDate 列中的字符串。您需要确定您正在使用的数据类型。
    • 那么我应该使用例外吗?
    • @s.23 我不知道,这是你的代码。您可以使用异常或确保所有行都有有效数据。
    • 我明白了,谢谢。 1-该异常会是什么样子? 2-您提到将字符串转换为日期对象这也有助于解决浮动问题吗?
    猜你喜欢
    • 2018-11-01
    • 1970-01-01
    • 2016-03-13
    • 2018-10-21
    • 2019-01-27
    • 2021-04-17
    • 2014-12-31
    • 2013-10-02
    • 2021-08-07
    相关资源
    最近更新 更多