I have couple columns in df with avg time, example "0 days 00:00:21". I want convert all columns to datetime.time format "hh:mm:ss" without "0 days". How can I do this?
2 Answers
Should be fine with that code
For 4 columns, u can create a list of column names that u want to change. After that, put into for loop to iterate all column names that u want to change. It'll convert columns.
column_names = ["first","second","third","fourth"]
for name in column_names:
df[name] = df[name].dt.seconds.apply(lambda x: pd.to_datetime(x, unit='s').time())
8 Comments
Grzegorz Z
it's working but only for one column, i have in my df 9 columns and i need change 4 columns and leave the rest unchanged
msamedozmen
can u sent your all table so I can take look according that. @GrzegorzZ
Grzegorz Z
I attached an image in the first message
msamedozmen
@GrzegorzZ I changed code, u can put your column names which u want to change into column_names list and it will convert all your columns
Grzegorz Z
it's working :-) maybe you know why I'm getting the message? "A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead"
|
not sure how you data is stored.. but you could try something like this:
# Example DataFrame
data = {'time1': ['0 days 00:00:21', '0 days 00:01:15', '0 days 00:02:45'],
'time2': ['0 days 00:00:35', '0 days 00:00:50', '0 days 00:03:10']}
df = pd.DataFrame(data)
# Convert columns to timedelta objects
df[['time1', 'time2']] = df[['time1', 'time2']].apply(pd.to_timedelta)
# Extract time component and convert to string
df[['time1', 'time2']] = df[['time1', 'time2']].applymap(lambda x: x.seconds)
# Convert seconds to hh:mm:ss format
df[['time1', 'time2']] = df[['time1', 'time2']].applymap(lambda x: pd.to_datetime(x, unit='s').time())
print(df)`
5 Comments
Grzegorz Z
my df have 9 columns: dtypes: int32(1), int64(3), object(2), timedelta64[ns](4). "unit='s' not valid with non-numerical val='0 days 00:00:21', at position 0 "
Max888
what data type is the avg time value?
Grzegorz Z
timedelta64[ns]
Max888
ok, you need to provide a reproducible data in a format I can see.
Grzegorz Z
I attached an image in the first message
datetime.timedeltaobjects in the DF? What's your end goal here with the format?