我刚刚将我的Pandas从0.11升级到0.13.0rc1.现在,该应用程序正在弹出许多新的警告.其中一个是这样的:
E:\FinReporter\FM_EXT.py:449: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
quote_df['TVol'] = quote_df['TVol']/TVOL_SCALE
Run Code Online (Sandbox Code Playgroud)
我想知道究竟是什么意思?我需要改变什么吗?
如果我坚持使用,我应该如何暂停警告quote_df['TVol'] = quote_df['TVol']/TVOL_SCALE?
def _decode_stock_quote(list_of_150_stk_str):
"""decode the webpage and return dataframe"""
from cStringIO import StringIO
str_of_all = "".join(list_of_150_stk_str)
quote_df = pd.read_csv(StringIO(str_of_all), sep=',', names=list('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefg')) #dtype={'A': object, 'B': object, 'C': np.float64}
quote_df.rename(columns={'A':'STK', 'B':'TOpen', 'C':'TPCLOSE', 'D':'TPrice', 'E':'THigh', 'F':'TLow', 'I':'TVol', 'J':'TAmt', 'e':'TDate', 'f':'TTime'}, inplace=True)
quote_df = quote_df.ix[:,[0,3,2,1,4,5,8,9,30,31]]
quote_df['TClose'] = quote_df['TPrice']
quote_df['RT'] …Run Code Online (Sandbox Code Playgroud) 关于可怕的问题,有无数的问题 SettingWithCopyWarning
我已经很好地理解了它是如何产生的.(注意我说好,不好)
当数据df帧通过存储的属性"附加"到另一个数据帧时,就会发生这种情况is_copy.
这是一个例子
df = pd.DataFrame([[1]])
d1 = df[:]
d1.is_copy
<weakref at 0x1115a4188; to 'DataFrame' at 0x1119bb0f0>
Run Code Online (Sandbox Code Playgroud)
我们可以将该属性设置为None或
d1 = d1.copy()
Run Code Online (Sandbox Code Playgroud)
我见过像@Jeff这样的开发者,我不记得还有谁,警告这样做.引用SettingWithCopyWarning有目的.
问题
好的,那么什么是一个具体的例子,说明为什么通过分配copy回原始来忽略警告是一个坏主意.
我会定义"坏主意"以澄清.
坏主意
这是一个坏主意来放置代码投入生产,这将导致越来越在星期六晚上说你的代码被打破,需要固定的中间一个电话.
现在如何使用df = df.copy()以绕过SettingWithCopyWarning导致获得那种电话.我想要它拼写出来,因为这是一个混乱的来源,我试图找到清晰度.我想看到爆炸的边缘情况!
我在pandas中设置了一个简单的DataFrame:
a = pandas.DataFrame([[1,2,3], [4,5,6], [7,8,9]], columns=['a','b','c'])
>>> print a
a b c
0 1 2 3
1 4 5 6
2 7 8 9
Run Code Online (Sandbox Code Playgroud)
我希望能够改变最后一行中的单个元素.在pandas == 0.13.1我可以使用以下内容:
a.iloc[-1]['a'] = 77
>>> print a
a b c
0 1 2 3
1 4 5 6
2 77 8 9
Run Code Online (Sandbox Code Playgroud)
但在更新到pandas == 0.14.1后,我在执行此操作时收到以下警告:
SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
Run Code Online (Sandbox Code Playgroud)
问题当然是-1不是索引a,所以我不能使用loc.正如警告所示,我没有更改 …
我正在尝试在数据框中作为字符串/对象类型的4个特定列上填充"".我可以将这些列分配给一个新的变量作为我的fillna(),但是当我在fillna()inplace中时,底层数据不会改变.
a_n6 = a_n6[["PROV LAST", "PROV FIRST", "PROV MID", "SPEC NM"]].fillna("")
a_n6
Run Code Online (Sandbox Code Playgroud)
给我:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1542 entries, 0 to 3611
Data columns (total 4 columns):
PROV LAST 1542 non-null values
PROV FIRST 1542 non-null values
PROV MID 1542 non-null values
SPEC NM 1542 non-null values
dtypes: object(4)
Run Code Online (Sandbox Code Playgroud)
但
a_n6[["PROV LAST", "PROV FIRST", "PROV MID", "SPEC NM"]].fillna("", inplace=True)
a_n6
Run Code Online (Sandbox Code Playgroud)
给我:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1542 entries, 0 to 3611
Data columns (total 7 columns):
NPI 1103 non-null values
PIN 1542 non-null …Run Code Online (Sandbox Code Playgroud) 如何计算人的年龄(基于dob列)并使用新值向数据框添加列?
dataframe如下所示:
lname fname dob
0 DOE LAURIE 03011979
1 BOURNE JASON 06111978
2 GRINCH XMAS 12131988
3 DOE JOHN 11121986
Run Code Online (Sandbox Code Playgroud)
我尝试过以下操作:
now = datetime.now()
df1['age'] = now - df1['dob']
Run Code Online (Sandbox Code Playgroud)
但是,收到以下错误:
TypeError:不支持的操作数类型 - :'datetime.datetime'和'str'
所以我使用了一个空的数据帧
df=data[['ID','Matrix','Name','Country', 'Units']]
df['Value']=''
Run Code Online (Sandbox Code Playgroud)
我用这样的代码填充它,它找到包含'Good','Bad'值的字符串df.Matrix并用以下值填充它们sch[i]:
df.loc[df.Matrix.str.contains('Good'),'Value'] = sch[2]
df.loc[df.Matrix.str.contains('Bad'),'Value'] = sch[6]
df.loc[df.Matrix.str.contains('Excellent'),'Value'] = sch[8]
Run Code Online (Sandbox Code Playgroud)
我遇到了一堆像这两个不同的错误:
C:\Python33\lib\site-packages\pandas\core\strings.py:184: UserWarning: This pattern has match groups. To actually get the groups, use str.extract.
" groups, use str.extract.", UserWarning)
C:\Users\0\Desktop\python\Sorter.py:57: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
df.loc[df.Matrix.str.contains('Bad'),'Value'] = sch[6]
Run Code Online (Sandbox Code Playgroud)
到目前为止,我正在使用压缩代码
pd.options.mode.chained_assignment = None
Run Code Online (Sandbox Code Playgroud)
如果我不压制错误消息,我将得到大约20个错误消息.是否有其他格式我可以更改数据,以便我不会收到错误消息?
我使用python 3和pandas 0.131如果它有帮助
In[216]: foo = pd.DataFrame({'a':[1,2,3], 'b':[3,4,5]})
In[217]: bar = foo.ix[:1]
In[218]: bar
Out[218]:
a b
0 1 3
1 2 4
Run Code Online (Sandbox Code Playgroud)
视图按预期创建.
In[219]: bar['a'] = 100
In[220]: bar
Out[220]:
a b
0 100 3
1 100 4
In[221]: foo
Out[221]:
a b
0 100 3
1 100 4
2 3 5
Run Code Online (Sandbox Code Playgroud)
如果修改了视图,原始数据帧foo也是如此.但是,如果使用"无"进行分配,则可能会生成副本.任何人都可以了解正在发生的事情以及背后的逻辑吗?
In[222]: bar['a'] = None
In[223]: bar
Out[223]:
a b
0 None 3
1 None 4
In[224]: foo
Out[224]:
a b
0 100 3
1 100 4
2 3 5
Run Code Online (Sandbox Code Playgroud) 在类的方法中,我使用以下语句:
self.__datacontainer.iloc[-1]['c'] = value
Run Code Online (Sandbox Code Playgroud)
这样做我得到一个“SettingWithCopyWarning:一个值正试图在来自 DataFrame 的切片的副本上设置”
现在我尝试重现此错误并编写以下简单代码:
import pandas, numpy
df = pandas.DataFrame(numpy.random.randn(5,3),columns=list('ABC'))
df.iloc[-1]['C'] = 3
Run Code Online (Sandbox Code Playgroud)
在那里我没有错误。为什么我在第一个语句中出现错误而不是在第二个语句中?
Pandas 版本0.23.4,python 版本3.7.1
我有一个数据框 df 如下
df = pd.DataFrame([[0.1, 2, 55, 0,np.nan],
[0.2, 4, np.nan, 1,99],
[0.3, np.nan, 22, 5,88],
[0.4, np.nan, np.nan, 4,77]],
columns=list('ABCDE'))
A B C D E
0 0.1 2.0 55.0 0 NaN
1 0.2 4.0 NaN 1 99.0
2 0.3 NaN 22.0 5 88.0
3 0.4 NaN NaN 4 77.0
Run Code Online (Sandbox Code Playgroud)
我想替换列中的 Na 值B和C列“A”中的值。
预期输出是
A B C D E
0 0.1 2.0 55.0 0 NaN
1 0.2 4.0 0.2 …Run Code Online (Sandbox Code Playgroud)