https://stackoverflow.com/questions/36928487/a-value-is-trying-to-be-set-on-a-copy-of-a-slice-from-a-dataframe
df = pd.DataFrame({'period': ['Q1', 'Q2', 'Q3', 'Q4', 'Q5'], 'qtr': [1, 2, 3, 4, 5]})
period |
qtr |
Q1 |
1 |
Q2 |
2 |
Q3 |
3 |
Q4 |
4 |
Q5 |
5 |
1. map解决---这个还是有copywarning
quarter = {"Q1": "Mar", "Q2": "Jun", "Q3": "Sep", "Q4": "Dec"}
df['period'] = df['period'].astype(str).map(quarter)
period |
qtr |
Mar |
1 |
Jun |
2 |
Sep |
3 |
Dec |
4 |
NaN |
5 |
2. assign
Unmapped values unchanged
df = df.assign(period=[quarter.get(q, q) for q in df.period])
period |
qtr |
Mar |
1 |
Jun |
2 |
Sep |
3 |
Dec |
4 |
5 |
5 |
Unmapped values get NaN
df = df.assign(period=df.period.map(quarter))
period |
qtr |
Mar |
1 |
Jun |
2 |
Sep |
3 |
Dec |
4 |
NaN |
5 |
df[df['A'] > 2]['B'] = new_val # new_val not set in df
The warning offers a suggestion to rewrite as follows:
df.loc[df['A'] > 2, 'B'] = new_val