首页 > 解决方案 > pandas 值正在尝试在 DataFrame 中的切片副本上设置

问题描述

这是我的代码:我的数据框 DF 基于此: index int64 FiscalYear int64 GL object GLID int64 GL_Debit float64 GL_Credit float64 month object Solde de fin float64

DF.sort_values(by=['GL', 'month'], inplace=True)
                    DF['Variation des périodes'] = DF.groupby([ 'GL'])['Solde de fin'].diff().fillna(DF['Solde de fin'])
                    DF = DF.rename(columns={'GL_Debit':'Débit année à date','GL_Credit':'Crédit année à date'})
            
for i in range(len(DF)):
                row = DF.iloc[i]
                teste = row['month'][5:7]
                if row['month'][5:7]=='04':
                    if row['GL'][0] in ['4', '5', '6', '7', '8', '9']:
                        DF.iloc[i]['Variation des périodes'] = row['Solde de fin']
                    else:
                        DF.iloc[i]['Variation des périodes'] = row['Variation des périodes']

我有这个错误: SettingWithCopyWarning: A value is trying to be set on a slice of a copy from a DataFrame DF.iloc[i]['Variation des périodes'] = row['Solde de fin']

DF.iloc[i]['Variation des périodes'] 没有显示行 ['Solde de fin']

标签: pythonpandas

解决方案


我找到了一个解决方案:用 loc 替换 bloc 并且没有警告并且值是上帝!

DF.loc[i, 'Variation des périodes'] =row['Solde de fin']

推荐阅读