0

Here my problem (assume that I already imported Pandas as pd and so on...):

I have a data frame called "x" It contains several columns, one of them called "Time" Time has dates in the format: Tue, 01 Jan 2019 18:09:17 GMT I want to transform those dates into the format: '%a, %d %b %Y %H:%M:%S %Z'

Here is where the problem starts First I tried: x['connectionTime'] = pd.to_datetime(x['connectionTime'], format='%a, %d %b %Y %H:%M:%S %Z') I got the error

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

then I tried: x.loc[:, 'connectionTime'] = pd.to_datetime(x_before.loc[:, 'connectionTime'] , format='%a, %d %b %Y %H:%M:%S %Z') and I got the error:

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

finally if I do: x_t = pd.to_datetime(x['connectionTime'], format='%a, %d %b %Y %H:%M:%S %Z') THIS WORKS!!! BUT x_before.loc[:, 'connectionTime'] = x_t gives the error:

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

I really do not know what else I should try.

THANKS!!!!

  • you should be able to just directly give the column any name you like, clobbering the old one `df["foo"] = pd.to_datetime(df["foo"], *args)`; `pd.to_datetime()` should return the same type it was given, which in this case is a Series https://pandas.pydata.org/docs/reference/api/pandas.to_datetime.html .. the DataFrame you're working with is probably being abused _earlier_ than this step – ti7 Apr 11 '23 at 20:24
  • if you're filtering values out of that column, you may want to do something like `.dropna()` or coerce to `NaT` when making the column values a datetime `pd.to_datetime(Series, other args, errors=coerce)` instead – ti7 Apr 11 '23 at 20:27

1 Answers1

-1

On way to do this would be to use the apply function https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html

You can either create a new column or override the existing column.

Basti
  • 1
  • 2