morais12
morais12

Reputation: 33

Change all the values in a column based on column index?

I have a dataframe.

   0  1  2
0  1  2  3
1  4  5  6
2  7  8  9

I have a list of column indexes for a dataframe.

list = [0,2]

For each column index in that list, I want to change the values via .apply. Normally, I would have the column names in the list and do something like this:

for column in list:
    df[column] = df[column].apply(x)

However, this dataframe contains duplicate column names, so I can't use column names. What is the best way to apply changes to a column's values, only knowing the column index?

Upvotes: 0

Views: 38

Answers (1)

Vivek Kalyanarangan
Vivek Kalyanarangan

Reputation: 9081

Use -

list_ = [0,2]
for i in list_:
    df.iloc[:, i] = df.iloc[:, i].apply(lambda x: x+1)

Output

    0   1   2
0   2   2   4
1   5   5   7
2   8   8   10

Upvotes: 2

Related Questions