mattator
mattator

Reputation: 339

update a dataframe at indices returned by query

I would like to have query return a view so that I can modify fields without generating this error.

SettingWithCopyWarning: 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

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

I have a multiline (long) query q that I abbreviated here:

df1 = pd.Dataframe(...)
q = "tcpstream==1  and ipsrc=='10.0.0.1' and sport==5201"
df = df1.query(q)    
df['dest'] = "toto"   # <--- this generates the warning/error

Apparently I could do a df1.update(df) but it seems like a waste, I am looking for something more efficient.

Upvotes: 1

Views: 59

Answers (1)

jpp
jpp

Reputation: 164633

pd.DataFrame.query is designed for querying, not setting values. If you want to use string queries as masks, you can calculate the index and feed into pd.DataFrame.loc:

df.loc[df.query(q).index, 'dest'] = 'toto'

Upvotes: 1

Related Questions