0

Need to change the values of city into Pune expect Bangalore.

sample input Data:

 EmployeeId     city     join_month
0   001        Mumbai        1
1   001        Bangalore     3
2   002        Pune          2
3   002        Mumbai        6
4   003        Delhi         9
5   003        Mumbai        12
6   004        Bangalore     11
7   004        Pune          10
8   005        Mumbai         5

Output sample:

 EmployeeId    city     join_month
0   001        Pune          1
1   001        Bangalore     3
2   002        Pune          2
3   002        Pune          6
4   003        Pune          9
5   003        Pune          12
6   004        Bangalore     11
7   004        Pune          10
8   005        Pune          5
desertnaut
  • 57,590
  • 26
  • 140
  • 166
Manoj Kumar
  • 15
  • 1
  • 6
  • maybe you should add an output sample to help people understanding it. – Ferris Feb 07 '21 at 10:19
  • 1
    All sorts of options from [previous answers](https://stackoverflow.com/questions/31511997/pandas-dataframe-replace-all-values-in-a-column-based-on-condition) – Chris Geatch Feb 07 '21 at 10:44
  • Does this answer your question? [Pandas DataFrame: replace all values in a column, based on condition](https://stackoverflow.com/questions/31511997/pandas-dataframe-replace-all-values-in-a-column-based-on-condition) – Grzegorz Skibinski Feb 07 '21 at 11:15

2 Answers2

0

Look like you have a data frame already. Using pandas, you can modify columns like this:

You can look at your columns using:

df.columns

To change the column names:

df.columns = ["Employee_ID", "City", "Month_Joined"

To change a single value in your city column, you can use the code below for each city value you want to change. 0 is the row, city is the column name, and Pune is what you want to change it to:

df.loc[0, "city"] = "Pune"

To change multiple values to in the city column to a single value. You are accessing the column city and replacing all occurrences of Mumbai and Delhi with Pune.

cityChange = df["city"] = df["city"].replace(["Mumbai", "Delhi"], "Pune")
live405
  • 26
  • 2
  • Thanks! But I have 802 rows and different values in the column. It might be difficult to change them one by one. Is their any other technique? @live405 – Manoj Kumar Feb 07 '21 at 10:33
  • Arguably the question is 1) how to *locate* other cities 2) how to change them to `"Pune"`. You have answered only the 2nd. – desertnaut Feb 07 '21 at 10:34
  • Ahh sorry, I have done it before but don’t have the code on me. I will work on it tomorrow if is not already solved by then, sorry I couldn’t help :) – live405 Feb 07 '21 at 10:36
  • I have update my answer, I hope that it helps. – live405 Feb 08 '21 at 01:21
0

use np.where will be work.

  1. find the city is eq Bangalore
  2. if the city is Bangalore not change, else change to Pune.
cond = df['city'] == 'Bangalore'
df['city'] = np.where(cond, 'Bangalore', 'Pune')
Ferris
  • 5,325
  • 1
  • 14
  • 23