anon_swe
anon_swe

Reputation: 9345

Trouble Applying Function to Each Cell in Pandas DataFrame

I have a Pandas DataFrame with a single column ('publish_time') of type datetime. I want to just get the times, so I tried something like this:

df.applymap(datetime.time)

Unfortunately, I get a TypeError:

TypeError: ('an integer is required', u'occurred at index publish_time')

I'm a little lost here because I'm applying a datetime function to a bunch of datetime objects, so I don't know why Python expects an integer. Any suggestions?

Thanks!

Upvotes: 1

Views: 40

Answers (1)

user2285236
user2285236

Reputation:

With the dt accessor, you can get the time component in a vectorized way:

df = pd.DataFrame({'publish_time': ['20170606 12:04', '20170606 17:02']})

df
Out: 
     publish_time
0  20170606 12:04
1  20170606 17:02

df['publish_time'] = pd.to_datetime(df['publish_time'])

df['publish_time'].dt.time
Out: 
0    12:04:00
1    17:02:00
Name: publish_time, dtype: object

Upvotes: 4

Related Questions