Home > other >  How to subtract one from every number that is present in a pandas dataframe?
How to subtract one from every number that is present in a pandas dataframe?

Time:10-18

I have a pandas dataframe, that looks like this.

User    item    Q8_1    Q8_3    Q8_4    Q9_1    Q9_2    Q9_3    Q9_5    Q10_1   ... Q14_1
0   1a  1-237a  4   5   5   5   5   5   4   5   ... 5   5   5   5   4   3   3   5   5   4
1   2a  1-237a  5   5   3   4   5   5   4   4   ... 4   4   4   5   5   4   5   5   5   4
2   3a  1-237a  4   3   2   2   4   5   2   2   ... 2   5   3   4   3   3   4   3   3   3
3   4a  1-237a  4   4   4   5   5   5   4   5   ... 4   5   5   5   4   4   4   4   5   5
4   5a  1-237a  4   3   5   6   5   5   4   3   ... 4   5   5   6   5   4   6   5   4   3

I want to decrement 1 from every integer value that are present in columns Q8_1 till last column.

CodePudding user response:

You can use slicing:

df.loc[:, 'Q8_1':] -= 1

CodePudding user response:

Option 1

One can use pandas.DataFrame.loc and a custom lambda function as follows

df.loc[:, 'Q8_1':] = df.loc[:, 'Q8_1':].apply(lambda x: x - 1)

[Out]:

  User    item  Q8_1  Q8_3  Q8_4  ...  Q15_4  Q15_5  Q24_3  Q24_6  Q24_8
0   1a  1-237a     3     4     4  ...      2      2      4      4      3
1   2a  1-237a     4     4     2  ...      3      4      4      4      3
2   3a  1-237a     3     2     1  ...      2      3      2      2      2
3   4a  1-237a     3     3     3  ...      3      3      3      4      4
4   5a  1-237a     3     2     4  ...      3      5      4      3      2

Option 2

For those that don't want to use .apply() as per the first note below, one alternative is doing the following

df.loc[:, 'Q8_1':] = df.loc[:, 'Q8_1':] - 1

[Out]:
  User    item  Q8_1  Q8_3  Q8_4  ...  Q15_4  Q15_5  Q24_3  Q24_6  Q24_8
0   1a  1-237a     3     4     4  ...      2      2      4      4      3
1   2a  1-237a     4     4     2  ...      3      4      4      4      3
2   3a  1-237a     3     2     1  ...      2      3      2      2      2
3   4a  1-237a     3     3     3  ...      3      3      3      4      4
4   5a  1-237a     3     2     4  ...      3      5      4      3      2

Option 3

One can also use pandas.DataFrame.loc and .sub(1) as follows

df.loc[:, 'Q8_1':] = df.loc[:, 'Q8_1':].sub(1)

[Out]:
  User    item  Q8_1  Q8_3  Q8_4  ...  Q15_4  Q15_5  Q24_3  Q24_6  Q24_8
0   1a  1-237a     3     4     4  ...      2      2      4      4      3
1   2a  1-237a     4     4     2  ...      3      4      4      4      3
2   3a  1-237a     3     2     1  ...      2      3      2      2      2
3   4a  1-237a     3     3     3  ...      3      3      3      4      4
4   5a  1-237a     3     2     4  ...      3      5      4      3      2

Notes:

  • Related