2017-04-22 84 views
0

我有一列有格式为hhmm的值,例如:1243。我需要从这一栏中拿出......(i,e 12)。请告知 hhmm的列格式为int将hhmms转换为hh在熊猫数据框中

+1

'df ['col'] // 100'? – Psidom

+0

如果它是一个字符串,则使用'df ['col']。str [:2]' – MaxU

回答

0

如果您的列具有Timestamp或Datetime类似的值,请使用.hour方法。

import pandas 
dr = pandas.date_range('2017-01-01T11:30:00Z', '2017-02-01T11:30:00Z', freq='D') 
data = pandas.Series(range(len(dr), index=dr) 
data.index.map(lambda x: x.hour) 

或者,如果你有一个数据帧:

df['times'] = df['times'].map(lambda x: x.hour) 
0

如果你的列是int,下面应该工作:

import pandas as pd 

df = pd.DataFrame() 
df['hhmm_format'] = [1243, 1151, 1211] 

df['hh_only'] = df['hhmm_format'].apply(lambda x: str(x)[:2]) 

df 

hhmm_format hh_only 
0 1243 12 
1 1151 11 
2 1211 12 

如果您需要转换回:

df.hh_only = pd.to_numeric(df.hh_only)