简体   繁体   English

如何使用 Numpy 通过来自另一个 DataFrame 的因子来缩放 DataFrame 中的列

[英]how to scale columns in a DataFrame by factors from another DataFrame using Numpy

To Scale each columns (A, B, C) in a DataFrame df:要缩放 DataFrame df 中的每一列(A、B、C):

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:在 DataFrame 缩放中使用缩放因子:

scaling = pd.DataFrame(dict(id=['B', 'A','C'], scaling = [0.2, 0.3, 0.4]))

using Numpy:使用 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?如何使用 Numpy 从对应的 id ['B', 'A','C'] 缩放中获得正确的因子?

I expected to have the following result with print(df)我希望使用 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 .目标只是将scaling为可以轻松应用于 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 :它可以乘以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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从另一个 Pandas dataframe 逐列缩放 - how to scale columns by column from another Pandas dataframe 如何根据在另一个 dataframe 中定义的行/列缩放因子来缩放 pandas dataframe? - How can I scale a pandas dataframe based on row/column scaling factors defined in another dataframe? Pandas - 如何使用另一个 dataframe 从 dataframe 中提取列? - Pandas - How to extract columns from a dataframe using another dataframe? 如何使用 numpy 基于来自另一列的子字符串在 DataFrame 中创建新列 - How to create new column in DataFrame based on substrings from another columns using numpy 如何将数据框中的列合并到另一个数据框 - how to merge columns from a dataframe to another dataframe 如何通过传递数据框列从另一个数据框列搜索索引 - how to search index from another dataframe columns by passing dataframe columns 使用 .to_numpy() 将特定列从 Pandas Dataframe 的一行复制到另一行 - Using .to_numpy() to copy specific columns from one row of Pandas Dataframe to another 如何根据另一个数据框中的变量从数据框中选择列 - How to select columns from the dataframe based on variables from another dataframe 如何使用另一个数据帧的子集填充数据框的列? - How to populate columns of a dataframe using a subset of another dataframe? 如何从另一个数据帧的列值估算一个数据帧中的列值 - How to impute columns value in one dataframe from that of another dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM