简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM