To Scale each columns (A, B, C) in a DataFrame df:
l1 = [1,2,3]
l2 = [4,5,6]
l3 = [7,8,9]
df = pd.DataFrame([z for z in zip(l1,l2,l3)], columns= ['A', 'B', 'C'])
with scaling factors in a DataFrame scaling:
scaling = pd.DataFrame(dict(id=['B', 'A','C'], scaling = [0.2, 0.3, 0.4]))
using Numpy:
df = pd.DataFrame(np.array(df)*np.array(scaling['scaling']), columns=df.columns)
How to obtain right factors from scaling with the corresponding id ['B', 'A','C'] using Numpy?
I expected to have the following result with print(df)
A B C
0 0.3 0.8 2.8
1 0.6 1.0 3.2
2 0.9 1.2 3.6
Try something like:
import pandas as pd
l1 = [1, 2, 3]
l2 = [4, 5, 6]
l3 = [7, 8, 9]
df = pd.DataFrame([z for z in zip(l1, l2, l3)], columns=['A', 'B', 'C'])
scaling = pd.DataFrame(dict(id=['B', 'A', 'C'], scaling=[0.2, 0.3, 0.4]))
# Get Scaling Into a more Usable Format
scaling = scaling.set_index('id').reindex(df.columns).to_numpy().reshape(1, -1)
# Perform scaling
scaled_df = df * scaling
print(scaled_df)
The goal is to just get scaling
into a shape that can be easily applied to the DataFrame scaling
. Once scaling is in the right shape and order:
scaling
A 0.3
B 0.2
C 0.4
[[0.3 0.2 0.4]]
It can just be multiplied by the df
:
A B C
0 0.3 0.8 2.8
1 0.6 1.0 3.2
2 0.9 1.2 3.6
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.