3

I have a column which is in datetime format and I want to change it to be date format.

db['Date'] = db['Date'].apply(lambda x: x.date())

And then I got a warning:

__main__:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead

I did some search and changed it to be:

db.loc[:,'Date'] = db.loc[:,'Date'].apply(lambda x: x.date())

The error message is:

    if isnull(other) or (np.isscalar(other) and other == tslib.iNaT):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

This error also happens when I tried to assign new values to a series:

db['new'] = db.apply(lambda x: my_func(x['A'],x['B']))

Could anyone suggest what is happening here and how can I get rid of the warnings?

I noticed that I can turn the warning off by setting db.is_copy = False but I'd rather keep it there in case I indeed have important errors. So I still hope to do something to make the code running adequately without warning messages.

Thanks in advance.

lsheng
  • 3,539
  • 10
  • 33
  • 43
  • pls show all code since you created this frame and pandas versions. why are you trying to convert to a datetime.date? – Jeff Mar 12 '14 at 01:42
  • db is reading from excel, then I did "db['Date'] = db['Date'].apply(lambda x: x.date())" immediately. – lsheng Mar 12 '14 at 02:01
  • Better to go to numpy's datetime using `pd.to_datetime(df['Date'])` – Andy Hayden Mar 12 '14 at 02:25
  • @AndyHayden db['Date'] is already a datetime, I just want a date format. And to change it I think I still need to assign db['Date'] by db['Date'] = pd.to_datetime(db['Date']) --- but whenever I used the equal sign I got the warnings mentioned in the OP – lsheng Mar 12 '14 at 03:24
  • but **why** do you want to make it a date format ? – Andy Hayden Mar 12 '14 at 04:37
  • Well I firstly thought that my post-calculations needs date format. But maybe datetime will also work. But same issues arises no matter which functions I'm adding in the lambda statements. So just look at this as an example.. My point is, no matter what functions Im using, if I wanted to change or create new columns in a dataframe same issues rise up all the time. – lsheng Mar 12 '14 at 05:55
  • pls show your code exactly – Jeff Mar 12 '14 at 09:11

1 Answers1

0

I set values using

df['THING'] = df['THING'].apply(function)

all the time. As Wes points out in his notes on the subject, the warning is a heuristic. It's not always the case that when you're assigning in this way, you're setting on a view. Make the assignment, then call df.head() (or whatever) and see if your frame has actually changed. If it has, who cares if there's a warning?

Nick Marinakis
  • 1,776
  • 2
  • 10
  • 12