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
205 views
in Technique[技术] by (71.8m points)

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

I have a dataframe column period that has values by Quarters(Q1,Q2,Q3,Q4) that I want to convert into associated month (see dict). My code below works however wondering why I'm getting this warning.

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

quarter = {"Q1":"Mar","Q2":"Jun","Q3":"Sep","Q4":"Dec"}
df['period'] = df['period'].astype(str).map(quarter)
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

"A value is trying to be set on a copy of a slice from a DataFrame" is a warning. SO contains many posts on this subject.

df.assign was added in Pandas 0.16 and is a good way to avoid this warning.

quarter = {"Q1": "Mar", "Q2": "Jun", "Q3": "Sep", "Q4": "Dec"}
df = pd.DataFrame({'period': ['Q1', 'Q2', 'Q3', 'Q4', 'Q5'], 'qtr': [1, 2, 3, 4, 5]})

df
  period  qtr
0     Q1    1
1     Q2    2
2     Q3    3
3     Q4    4
4     Q5    5

df = df.assign(period=[quarter.get(q, q) for q in df.period])

# Unmapped values unchanged.
>>> df
  period  qtr
0    Mar    1
1    Jun    2
2    Sep    3
3    Dec    4
4     Q5    5

df = pd.DataFrame({'period': ['Q1', 'Q2', 'Q3', 'Q4', 'Q5'], 'qtr': [1, 2, 3, 4, 5]})
df = df.assign(period=df.period.map(quarter))

# Unmapped values get `NaN`.
>>> df
  period  qtr
0    Mar    1
1    Jun    2
2    Sep    3
3    Dec    4
4    NaN    5

Assign new columns to a DataFrame, returning a new object (a copy) with all the original columns in addition to the new ones.

.. versionadded:: 0.16.0


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

...