【问题标题】:How to apply df.min() and df.max() distributively over many DataFrames如何将 df.min() 和 df.max() 分布应用于许多 DataFrame
【发布时间】:2018-06-27 19:11:16
【问题描述】:

我有一个 DataFrame 列表,所有列都具有相同的列,并且希望将所有这些中的值标准化为 [0, 1],同时还保持 DataFrame 之间值的相对缩放。

对于单个 DataFrame,我可以这样做:

df = (df - df.min()) / (df.max() - df.min())

但是,我怎样才能获得所有 DataFrame 中每列的最小值和最大值,然后将与上述相同的公式应用于每个单独的 DataFrame,使用每列的集合最小值和最大值?

这是一个包含 2 个 DataFrame 的示例列表,每个 DataFrame 在其上单独标准化:

import numpy as np
import pandas as pd

dfs = []

for i in range(2):
    data = np.random.rand(3, 3)
    df = pd.DataFrame(data, columns=["one", "two", "three"])
    dfs.append(df)
    print(df)

for i in range(2):
    dfs[i] = (dfs[i] - dfs[i].min()) / (dfs[i].max() - dfs[i].min())
    print(dfs[i])

【问题讨论】:

  • 啊,你有多个列。您想要按列还是按数据框进行标准化?
  • 所有数据帧中的每列

标签: python pandas dataframe normalization


【解决方案1】:

我将concat dfs 转换为一个 df,并使用 multiindex 进行计算

df=pd.concat(dfs,keys=range(len(dfs)))
df =df.groupby(level=0).apply(lambda x : (x - x.min()) / (x.max() - x.min()))

如果你想看第一个 df

df.loc[0]
Out[20]: 
        one       two     three
0  1.000000  0.576142  0.000000
1  0.559371  0.000000  1.000000
2  0.000000  1.000000  0.594986

【讨论】:

  • 非常优雅,谢谢。关于 DataFrame,我什至不知道 keys
  • @KOB Yw~ :-) 快乐编码
  • 我刚刚注意到这仍然会在连接的数据帧中单独标准化每个数据帧。将第二行简单地更改为 df = (df - df.min()) / (df.max() - df.min()) 可以解决此问题,然后我可以将键上的连接 df 拆分回列表中。
猜你喜欢
  • 1970-01-01
  • 2020-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-10
  • 1970-01-01
  • 2018-09-23
相关资源
最近更新 更多