python dataframe切片_python-如何避免“试图在DataFrame的切片副本上设置值”?
我有一個數(shù)據(jù)框df_original:
a b
0 10 5
1 12 6
2 14 1
現(xiàn)在,我想制作一個包含所有行的新數(shù)據(jù)框,其中c> 5,然后在此新數(shù)據(jù)幀上設(shè)置新的列值:
df = df_original[df_original['b'] > 5]
df['c'] = df['a'] / df['b']
但是我得到一個警告:
/Library/Python/2.7/site-packages/ipykernel/__main__.py:25: 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
如果c不回到原始數(shù)據(jù)框,我會很高興.但是如何正確執(zhí)行此操作并避免警告?
解決方法:
采取copy以避免警告:
In [118]:
df1 = df[df['b'] > 5].copy()
df1['c'] = df1['a'] / df1['b']
df1
Out[118]:
a b c
1 12 6 2.0
這樣可以避免通話中的歧義
標(biāo)簽:pandas,python
來源: https://codeday.me/bug/20191118/2031218.html
總結(jié)
以上是生活随笔為你收集整理的python dataframe切片_python-如何避免“试图在DataFrame的切片副本上设置值”?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: int*类型和int类型_mysql8.
- 下一篇: python储存与读取图片_Python