简体   繁体   English

如何在不获取 SettingWithCopyWarning 的情况下修改 DataFrame 列?

[英]How to modify DataFrame column without getting SettingWithCopyWarning?

I have a DataFrame object df .我有一个DataFrame对象df And I would like to modify job column so that all retired people are 1 and rest 0 (like shown here ):我想修改job列,使所有退休人员为1和0休息(如显示这里):

df['job'] = df['job'].apply(lambda x: 1 if x == "retired" else 0)

But I get a warning:但我收到警告:

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

Why did I get it here though?可为什么我会在这里得到它? From what I read it applies to situations where I take a slice of rows and then a column, but here I am just modyfing elements in a row.从我读到的内容来看,它适用于我先取一行然后取一列的情况,但在这里我只是修改一行中的元素。 Is there a better way to do that?有没有更好的方法来做到这一点?

Use:用:

df['job']=df['job'].eq('retired').astype(int)

or或者

df['job']=np.where(df['job'].eq('retired'),1,0)

So here's an example dataframe:所以这是一个示例数据框:

import pandas as pd
import numpy as np

data = {'job':['retired', 'a', 'b', 'retired']}
df = pd.DataFrame(data)
print(df)

       job
0  retired
1        a
2        b
3  retired

Now, you can make use of numpy's where function:现在,您可以使用 numpy 的where函数:

df['job'] = np.where(df['job']=='retired', 1, 0)
print(df)

   job
0    1
1    0
2    0
3    1

I would not suggest using apply here, as in the case of large data frame it could lower your performance.我不建议在此处使用 apply,因为在大型数据框的情况下,它可能会降低您的性能。

I would prefer using numpy.select or numpy.where .我更喜欢使用numpy.selectnumpy.where

See This And This 看到这个和这个

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在不获取 SettingWithCopyWarning 的情况下有效更新数据框的列? - How to effectively update a dataframe's column without getting a SettingWithCopyWarning? 如何在避免 SettingWithCopyWarning 的同时修改 Pandas DataFrame 中的整数值? - How to modify integer values in a Pandas DataFrame whilst avoiding SettingWithCopyWarning? 无论如何,仍然在 Pandas dataframe 列分配中得到 SettingWithCopyWarning - No matter what, still getting SettingWithCopyWarning in Pandas dataframe column assignment 将DataFrame slice作为参数传递给函数,而无需'SettingWithCopyWarning' - Passing DataFrame slice as argument to function without 'SettingWithCopyWarning' 将空列添加到 Pandas 中的 dataframe 时的 SettingWithCopyWarning - SettingWithCopyWarning when adding an empty column to a dataframe in Pandas 应用时获取SettingWithCopyWarning应用于DataFrame熊猫 - Getting SettingWithCopyWarning when applying apply on a DataFrame Pandas SettingWithCopyWarning Python在数据框中更改列数据类型 - SettingWithCopyWarning Python changing column datatype in Dataframe 当一行DataFrame是字符串时,SettingWithCopyWarning - SettingWithCopyWarning when one column of DataFrame is strings 如何修改/转换数据框的列? - How to modify/transform the column of a dataframe? 如何对数据框使用“应用”并避免SettingWithCopyWarning? - How to use “apply” with a dataframe and avoid SettingWithCopyWarning?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM