2

I have an example data as below:

datetime    x   y
2021-05-01. 25. val1
2021-05-02. 50. val2
2021-05-03. 100 val3
2021-05-04. 25.  val4
2021-05-05. 100. val5
2021-05-06. 50.  val6

I would like to create a new column calle z which maps 25 to low, 50 to medium and 100 to high with the expected output shown below:

datetime    x   y.     z
2021-05-01. 25. val1.  Low
2021-05-02. 50. val2.  Medium
2021-05-03. 100 val3.  High
2021-05-04. 25.  val4. Low
2021-05-05. 100. val5. High
2021-05-06. 50.  val6. Medium
StackUser
  • 425
  • 1
  • 3
  • 12
  • You can review this :https://stackoverflow.com/questions/19913659/pandas-conditional-creation-of-a-series-dataframe-column – pkd May 18 '21 at 09:07

3 Answers3

3

You can use numpy select:

conditions = [df['x'] == 25, df['x'] == 50, df['x'] == 100]
choices = ['Low', 'Medium', 'High']

df['z'] = np.select(conditions, choices)

Output:

       datetime    x       y       z
0   2021-05-01.   25.  val1.     Low
1   2021-05-02.   50.  val2.  Medium
2   2021-05-03.  100.  val3.    High
3   2021-05-04.   25.  val4.     Low
4   2021-05-05.  100.  val5.    High
5   2021-05-06.   50.  val6.  Medium

If format is string use:

conditions = [df['x'] == '25.', df['x'] == '50.', df['x'] == '100.']
Arkadiusz
  • 1,835
  • 1
  • 8
  • 15
2

You can use map:

d = {25:'Low',50:'Medium',100:'high'}
df['z'] = df['x'].map(d)

#       datetime      x     y       z
# 0  2021-05-01.   25.0  val1     Low
# 1  2021-05-02.   50.0  val2  Medium
# 2  2021-05-03.  100.0  val3    high
# 3  2021-05-04.   25.0  val4     Low
# 4  2021-05-05.  100.0  val5    high
# 5  2021-05-06.   50.0  val6  Medium
Andreas
  • 8,694
  • 3
  • 14
  • 38
1

There are four ways of converting integers to strings in pandas

1: frame[‘DataFrame Column’]= frame[‘DataFrame Column’].map(str)

2: frame[‘DataFrame Column’]= frame[‘DataFrame Column’].apply(str)

3: frame[‘DataFrame Column’]= frame[‘DataFrame Column’].astype(str)

4: frame[‘DataFrame Column’]= frame[‘DataFrame Column’].values.astype(str)