Prevent the following warnings from appearing! (The code that gives this warning is shown below)
aa.py:5: 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 the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
d['col3']= d['col2'] * 3
col1 col2 col3
0 1 2 6
2 1 2 6
http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
dfmi.loc[:,('one','second')] = value
# becomes
dfmi.loc.__setitem__((slice(None), ('one', 'second')), value)
It is written.
aa.py
import pandas as pd
data = pd.DataFrame([[1,2],[2,3],[1,2],[2,3]], columns=['col1','col2'])
d = data[data['col1'] == 1]
d['col3']= d['col2'] * 3
print(d)
If you do this, you will get the above Warning.
The problem lies in the following line.
d = data[data['col1'] == 1]
If this is d = data
, the above Warning is not available.
Since data has values other than col1 == 1, if you try to add a new Column to the DF that has been cut out by col1 == 1, it will be strange, so make it a copy and only col1 == 1 in advance Just make a DF.
Revised
d = data[data['aa'] == 2].copy()
As supported in the link above, use .loc
and update only the corresponding part.
Revised
#Put Value (right side) in col3 (new Column) although col1 meets the condition of 1.
data.loc[data['col1'] == 1, 'col3'] = data['col2'] * 3
#Extract only the part where col1 is 1 from data
d = data[data['col1'] == 1]
print('data:\n %s' % data)
print('d:\n%s' % d)
result
data:
col1 col2 col3
0 1 2 6
1 2 3 NaN
2 1 2 6
3 2 3 NaN
d:
col1 col2 col3
0 1 2 6
2 1 2 6
Recommended Posts