Search code examples
python-3.xpandasdataframepycharm

Selecting column location before modifying its data in Python Panda data frame


Panda beginner here.

I have below dataframe

Column1 Column2 Column3 Column12 Column13
A C E G I
B D F H J

I want to modify data if the column satisfy certain conditions. For example

If column.contains('2', case=False)

then I want to change the data value to 3

Expected result:

Column1 Column2 Column3 Column12 Column13
A 3 E 3 I
B 3 F 3 J

Solution

  • Use str.contains with boolean indexing:

    df.loc[:, df.columns.str.contains('2', case=False)] = 3
    

    NB. case does not matter for 2.

    output:

      Column1 Column2 Column3 Column12 Column13
    0       A       3       E        3        I
    1       B       3       F        3        J