Reputation: 745
I am looking to divide each pair of successive column and repopulate the calculated value. For example, I have the following DataFrame below. In the data frame below, I want to divide B/A and the D/C. Then the result of B/A should be repopulated in column B and the result of D/C should be populated in column D.
Note that my actual DataFrame is very large. It has 86 columns. I would prefer to have an automated scheme that either loops through all the columns (that is 86 columns) that changes the values in 43 columns or a built-in Pandas function that does this operation.
A B C D
0 2.056494 -3.002088 0.516822 -1.338846
1 0.082295 1.387734 -0.495226 1.119553
2 0.298618 -0.130158 0.804705 -0.120110
3 0.178088 1.137238 1.331856 -0.472720
4 -0.378670 1.649041 -0.240723 2.044113
5 3.602587 1.152502 -0.170646 -0.961922
6 -0.285846 -0.154891 1.492879 0.752487
7 -0.412809 1.076796 -2.001025 -0.954021
Thanks for reading this and appreciate your help.
Upvotes: 1
Views: 87
Reputation: 353059
You can use .iloc
to slice every other column, and then .values
to remove the indices on both axes so it'll align correctly:
>>> df.iloc[:, 1::2] /= df.iloc[:, ::2].values
>>> df
A B C D
0 2.056494 -1.459809 0.516822 -2.590536
1 0.082295 16.862920 -0.495226 -2.260691
2 0.298618 -0.435868 0.804705 -0.149260
3 0.178088 6.385820 1.331856 -0.354933
4 -0.378670 -4.354823 -0.240723 -8.491557
5 3.602587 0.319910 -0.170646 5.636944
6 -0.285846 0.541869 1.492879 0.504051
7 -0.412809 -2.608461 -2.001025 0.476766
.iloc
allows us to index positionally using the standard Python slicing:
>>> df.iloc[:, 1::2]
B D
0 -1.459809 -2.590536
1 16.862920 -2.260691
2 -0.435868 -0.149260
3 6.385820 -0.354933
4 -4.354823 -8.491557
5 0.319910 5.636944
6 0.541869 0.504051
7 -2.608461 0.476766
And without the .values
, we'd still have the column names, which would give us
>>> df.iloc[:, 1::2] / df.iloc[:, ::2]
A B C D
0 NaN NaN NaN NaN
1 NaN NaN NaN NaN
2 NaN NaN NaN NaN
3 NaN NaN NaN NaN
4 NaN NaN NaN NaN
5 NaN NaN NaN NaN
6 NaN NaN NaN NaN
7 NaN NaN NaN NaN
Upvotes: 5