Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

python pandas: how to avoid chained assignment

I have a pandas dataframe with two columns: x and value. I want to find all the rows where x == 10, and for all these rows set value = 1,000. I tried the code below but I get the warning that

A value is trying to be set on a copy of a slice from a DataFrame.

I understand I can avoid this by using .loc or .ix, but I would first need to find the location or the indices of all the rows which meet my condition of x ==10. Is there a more direct way?

Thanks!

import numpy as np
import pandas as pd

df=pd.DataFrame()
df['x']=np.arange(10,14)
df['value']=np.arange(200,204)


print df

df[ df['x']== 10 ]['value'] = 1000 # this doesn't work

print df
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should use loc to ensure you're working on a view, on your example the following will work and not raise a warning:

df.loc[df['x'] == 10, 'value'] = 1000

So the general form is:

df.loc[<mask or index label values>, <optional column>] = < new scalar value or array like>

The docs highlights the errors and there is the intro, granted some of the function docs are sparse, feel free to submit improvements.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...