A clean syntax for this kind of "find and replace" uses a dict, as
df.Num_of_employees = df.Num_of_employees.replace({"10-Jan": "1-10",
"Nov-50": "11-50"})
Answer from miriamsimone on Stack Overflowpython - Pandas replacing values on specific columns - Stack Overflow
Replacing certain values from entire columns of a pandas dataframe
Best way to replace values in one column from another column in pandas?
Re-Assign values in a specific dataframe column using .iloc[]
Here is the answer by one of the developers: https://github.com/pydata/pandas/issues/11984
This should ideally show a SettingWithCopyWarning, but I think this is quite difficult to detect.
You should NEVER do this type of chained inplace setting. It is simply bad practice.
idiomatic is:
In [7]: df[['A','B']] = df[['A','B']].replace([1, 3, 2], [3, 6, 7]) In [8]: df Out[8]: A B C 0 3 7 8 1 6 4 8 2 5 3 8(you can do with
df.loc[:,['A','B']]as well, but more clear as above.
to_rep = dict(zip([1, 3, 2],[3, 6, 7]))
df.replace({'A':to_rep, 'B':to_rep}, inplace = True)
This will return:
A B C
0 3 7 8
1 6 4 8
2 5 3 8
Hi, I created a pandas dataframe with one column called 'service' with 100+ rows. some of the values are 1, 2, and 3. i want to replace each with a word. so for example, whenever the value is 2, it instead prints as "Fun Pro". under the same column. thanks for any help
Original range:
| old_items | new_items |
|---|---|
| item1 | item6 |
| item2 | 0 |
| item3 | item7 |
| item4 | 0 |
| item5 | item8 |
Desired output:
| old_items | new_items |
|---|---|
| item6 | item6 |
| item2 | 0 |
| item7 | item7 |
| item4 | 0 |
| item8 | item8 |
My stupid solution:
old_items = list(df['old_items'])
new_items = list(df['new_items'])
proper_items = []
for x in range(len(old_items)):
if new_items[x] != 0:
proper_items.append(new_items[x])
else:
proper_items.append(old_items[x])
df['old_items'] = proper_items