-1

I have a column in data frame like this (an simplify example):

col
a
b
c
d
e
f
g

and I want to change the values like this:

col
a
b
other
other
other
other
other

I tried like this:

df = df.loc[df.col == ("a" or "b"), "col"] = "other"

but it does not work, I have an error:

AttributeError: 'str' object has no attribute 'loc'

Any advices?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
pd13
  • 13
  • 1
  • 5
  • 1
    your `df` somehow got replaced with a string value. that's why that error appears. and for the advice, see mosc9575 answer – dimas krisrianto Apr 17 '22 at 17:19
  • Don't change your question after accepting an answer. I've rolled back the edit. It'd be more appropriate to ask a new question, though in this case, I see your question has already been answered in the comments on mosc9575's answer. – wjandrea Dec 05 '22 at 17:31

1 Answers1

2

The problem with your code is, that df is changing to type string during the process.

There exists a pandas function for this usecase, named pd.where().

df = df.where(df['col'].isin(['a', 'b']),'other')

Similar result avoiding where():

df[~df['col'].isin(['a', 'b'])] = 'other'
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
mosc9575
  • 5,618
  • 2
  • 9
  • 32
  • About your solution, it is one problem. I probably I did not myself clear. I meant to change values into "other" only in that one column "col". Not in every column in row. – pd13 Apr 18 '22 at 12:04
  • 1
    This is also valid for a single column/Series. Use `df['col'].where()`. – mosc9575 Apr 18 '22 at 12:05
  • when I try: df = df["col"].where(df["col"].isin(["a", "b"]), "Other") I have got an error: AttributeError: 'Series' object has no attribute 'col' – pd13 Apr 18 '22 at 12:10
  • 1
    You have to apply this to only one column. Use `df["col"] = df["col"].where(df["col"].isin(["a", "b"]), "Other")` – mosc9575 Apr 18 '22 at 12:14
  • Thanks again for a quick reply! Works like it should. – pd13 Apr 18 '22 at 12:15