簡體   English   中英

如何從另一個 Pandas dataframe 逐列縮放

[英]how to scale columns by column from another Pandas dataframe

我有一個 Pandas 數據框“df”,我想在其中逐列執行一些縮放。

在“A”列中,我需要從 ID 為“A”的行對其進行縮放。 在“B”列中,我需要從 id 為“B”的行對其進行縮放。 ...

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=['A', 'B','C'], scaling = [0.2, 0.3, 0.4]))

最好的方法是什么?

怎么樣:

for col in df.columns:
    df[col] = df[col] * scaling.loc[scaling['id'] == col]["scaling"].item()

假設列是唯一的,並且在scaling中沒有重復,您可以使用map

df.mul(df.columns.map(scaling.set_index("id").scaling))

     A    B    C
0  0.2  1.2  2.8
1  0.4  1.5  3.2
2  0.6  1.8  3.6

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM