I have created a DataFrame:
import pandas as pd
import random
data = [[random.uniform(0, 1), random.uniform(0, 1), random.uniform(0, 1), random.uniform(0, 1), random.uniform(0, 1)], [random.uniform(0, 1), random.uniform(0, 1), random.uniform(0, 1), random.uniform(0, 1), random.uniform(0, 1)], [random.uniform(0, 1), random.uniform(0, 1),random.uniform(0, 1),random.uniform(0, 1),random.uniform(0, 1)], [random.uniform(0, 1), random.uniform(0, 1), random.uniform(0, 1), random.uniform(0, 1), random.uniform(0, 1)], [random.uniform(0, 1), random.uniform(0, 1), random.uniform(0, 1), random.uniform(0, 1), random.uniform(0, 1)], [random.uniform(0, 1), random.uniform(0, 1),random.uniform(0, 1),random.uniform(0, 1),random.uniform(0, 1)]]
df= pd.DataFrame(data, columns=["A","B", "C", "D", "E"])
The DataFrame looks like this:
A B C D E
0 0.736739 0.184075 0.727951 0.173798 0.184594
1 0.047031 0.567518 0.103112 0.094116 0.050785
2 0.955045 0.754968 0.235842 0.710304 0.109404
3 0.426293 0.617942 0.304042 0.043034 0.798327
4 0.415225 0.461497 0.263462 0.621364 0.974682
5 0.936775 0.822425 0.073169 0.634906 0.140092
What I want to do now is to divide certain columns for example with 2. In this case I'd like to divide column B, D, and E with two. For that I'd like to use a list. Becaus in my real Problem the Indices are Equity-names and the ones I'd like to divide are saved in a list.
That's what I tried:
list = ["B", "D", "E"]
df1 = df[df.columns.intersection(list)] *0.5
print(df1)
And the result looks like this:
B D E
0 0.092038 0.086899 0.092297
1 0.283759 0.047058 0.025392
2 0.377484 0.355152 0.054702
3 0.308971 0.021517 0.399164
4 0.230749 0.310682 0.487341
5 0.411212 0.317453 0.070046
But what I get is only a DataFrame which only contains the columns from the list. I'd like that my result would contain the new calculated value plus the old values from the columns which weren't in the list.
The result should look like this:
A B C D E
0 0.736739 0.092038 0.727951 0.086899 0.092297
1 0.047031 0.283759 0.103112 0.047058 0.025392
2 0.955045 0.377484 0.235842 0.355152 0.054702
3 0.426293 0.308971 0.304042 0.021517 0.399164
4 0.415225 0.230749 0.263462 0.310682 0.487341
5 0.936775 0.411212 0.073169 0.317453 0.070046
Does anyone know's how I can solve this problem? Your help is very appreciated.
Best regards!