2017-08-10 105 views
1

我有一个熊猫数据框,其日期列中的日期格式为“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中,请大家帮忙!

回答

0

我相信您的数据包含NaN S或一些不datetime值:

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]退货第一李首先每行的st值。但随后有问题 - 一些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转换为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 
对于删除 NaN小号

解决方案:

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.

通过dropnaNaN动手清除所有的行,然后浇铸到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。

通过fillna通过像1一些int值替换NaN秒,然后转换为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 
+0

非常感谢你的工作得很好! –

+0

嗯,你写评论与另一个解决方案的一些问题,所以另一个解决方案工作很好,所以是否接受? – jezrael

+0

接受。谢谢 –

0

您可以使用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(假设大熊猫版本> = 0.16)

+0

嘿@DeepSpace!谢谢你。我试过了,但是我收到了这个错误:AttributeError:'float'object has no attribute'split' –

+0

@ s.23很显然,有些行在'startDate'列中包含一个float对象而不是字符串。您需要确定您正在使用的数据类型。 – DeepSpace

+0

那么我应该使用异常? –

相关问题