2017-08-10 103 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

那麼我應該使用異常? –

相關問題