试图在DataFrame的切片副本上设置一个值 [英] A value is trying to be set on a copy of a slice from a DataFrame
问题描述
我有一个数据框列周期,该周期具有按季度(Q1,Q2,Q3,Q4)的值,我希望将其转换为关联的月份(请参见dict).下面的代码可以正常工作,但想知道为什么我会收到此警告.
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.
试图在DataFrame的切片副本上设置一个值. 尝试使用.loc [row_indexer,col_indexer] = value代替
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)
推荐答案
正在尝试从DataFrame的切片副本上设置值"是警告. SO包含许多与此主题相关的帖子.
"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
已在Pandas 0.16中添加,是避免此警告的好方法.
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
将新列分配给DataFrame,返回一个新对象 (副本)以及所有新的原始列.
Assign new columns to a DataFrame, returning a new object (a copy) with all the original columns in addition to the new ones.
..版本添加:: 0.16.0
.. versionadded:: 0.16.0
这篇关于试图在DataFrame的切片副本上设置一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!