SettingWithCopyWarning:试图在 DataFrame 警告的切片副本上设置值
SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame WARNING
求助。我尝试 运行 下面的代码:
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
import statsmodels.stats.multicomp as multi
#import data
df = pd.read_csv('nesarc2.csv', low_memory=False, na_values=' ')
#setting needed variables to numeric
df['CHECK321'] = pd.to_numeric(df['CHECK321'], errors='coerce')
df['S3AQ3B1'] = pd.to_numeric(df['S3AQ3B1'], errors='coerce')
df['S3AQ3C1'] = pd.to_numeric(df['S3AQ3C1'], errors='coerce')
df['S4AQ4A5'] = pd.to_numeric(df['S4AQ4A5'], errors='coerce')
#SETTING MISSING DATA
df['CHECK321']=df['CHECK321'].replace(9, np.nan)
df['S3AQ3B1']=df['S3AQ3B1'].replace(9, np.nan)
df['S3AQ3C1']=df['S3AQ3C1'].replace(99, np.nan)
df['S4AQ4A5']=df['S4AQ4A5'].replace(9, np.nan)
#subset data to young adults age 18 to 25 who have smoked in the past 12 months
data=df[(df['AGE']>=18) & (df['AGE']<=25) & (df['CHECK321']==1)]
#recoding number of days smoked in the past month
recode = {1: 30, 2: 22, 3: 14, 4: 5, 5: 2.5, 6: 1}
data['USFREQMO']= data['S3AQ3B1'].map(recode, inplace = True)
然后我得到以下错误:
C:\Users\Adeagbo Rapheal\anaconda3\lib\site-packages\pandas\core\generic.py:6746: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
即使我忽略警告并继续分析,我也无法使用该变量。
让我们修复
data=df[(df['AGE']>=18) & (df['AGE']<=25) & (df['CHECK321']==1)].copy()
data['USFREQMO'] = data['S3AQ3B1'].map(recode)
求助。我尝试 运行 下面的代码:
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
import statsmodels.stats.multicomp as multi
#import data
df = pd.read_csv('nesarc2.csv', low_memory=False, na_values=' ')
#setting needed variables to numeric
df['CHECK321'] = pd.to_numeric(df['CHECK321'], errors='coerce')
df['S3AQ3B1'] = pd.to_numeric(df['S3AQ3B1'], errors='coerce')
df['S3AQ3C1'] = pd.to_numeric(df['S3AQ3C1'], errors='coerce')
df['S4AQ4A5'] = pd.to_numeric(df['S4AQ4A5'], errors='coerce')
#SETTING MISSING DATA
df['CHECK321']=df['CHECK321'].replace(9, np.nan)
df['S3AQ3B1']=df['S3AQ3B1'].replace(9, np.nan)
df['S3AQ3C1']=df['S3AQ3C1'].replace(99, np.nan)
df['S4AQ4A5']=df['S4AQ4A5'].replace(9, np.nan)
#subset data to young adults age 18 to 25 who have smoked in the past 12 months
data=df[(df['AGE']>=18) & (df['AGE']<=25) & (df['CHECK321']==1)]
#recoding number of days smoked in the past month
recode = {1: 30, 2: 22, 3: 14, 4: 5, 5: 2.5, 6: 1}
data['USFREQMO']= data['S3AQ3B1'].map(recode, inplace = True)
然后我得到以下错误:
C:\Users\Adeagbo Rapheal\anaconda3\lib\site-packages\pandas\core\generic.py:6746: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
即使我忽略警告并继续分析,我也无法使用该变量。
让我们修复
data=df[(df['AGE']>=18) & (df['AGE']<=25) & (df['CHECK321']==1)].copy()
data['USFREQMO'] = data['S3AQ3B1'].map(recode)