python - 数字 : normalize column B according to value of column A

标签 python numpy pandas normalize

给定一个 NumPy 数组 [A B]A 是不同的索引和 B 计数值。 如何根据 A标准化 B 值?

我试过:

 def normalize(np_array):
    normalized_array = np.empty([1, 2])
    indexes= np.unique(np_array[:, 0]).tolist()

    for index in indexes:
        index_array= np_array[np_array[:, 0] == index]
        mean_id = np.mean(index_array[:, 1])
        std_id = np.std(index_array[:, 1])
        if mean_id * std_id > 0:
            index_array[:, 1] = (index_array[:, 1] - mean_id) / std_id
            normalized_array = np.concatenate([normalized_array, index_array])
    return np.delete(normalized_array, 0, 0) # my apologies

这是在做这项工作,但我正在寻找一种更崇高的方式来实现这一目标。

热烈欢迎任何意见。

最佳答案

看起来像pandas在这里可以提供帮助:

import pandas as pd

df = pd.DataFrame({'ID': [1, 1, 2, 2, 1],
                   'value': [10, 20, 15, 100, 12]})

byid = df.groupby('ID')
mean = byid.mean()
std = byid.std()

df['normalized'] = df.apply(lambda x: (x.value - mean.ix[x.ID]) / std.ix[x.ID], axis=1)
print(df)

输出:

   ID  value  normalized
0   1     10   -0.755929
1   1     20    1.133893
2   2     15   -0.707107
3   2    100    0.707107
4   1     12   -0.377964

来自 NumPy 数组:

>>> a
array([[  1,  10],
       [  1,  20],
       [  2,  15],
       [  2, 100],
       [  1,  12]])

您可以像这样创建数据框:

>>> df = pd.DataFrame({'ID': a[:, 0], 'value': a[:, 1]})
>>> df
   ID  value
0   1     10
1   1     20
2   2     15
3   2    100
4   1     12

关于python - 数字 : normalize column B according to value of column A,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35243847/

相关文章:

python - 计算两列中任一列中字符串出现次数的矢量化方法

python - 对 pandas 中的数据框进行排序

python - 从函数在数据框中创建多列

python-3.x - 如何将列内的值合并到 Pandas 中以逗号分隔的单行中?

python - "Cannot convert Python object argument to type ' <typename> '"- 使用 Cython 包装 C++ 类时出错

python - 使用 strptime 获取 UTC 偏移量,并在小时和分钟之间进行分隔

python - 如果前一行有感知变化,则替换值数据框列值

python - 我应该在模块的 requirements.txt 中包含 Sphinx 和/或 Nose 吗?

python - 在python中将文件从SMB服务器复制到本地驱动器(Linux/Windows)

python - 属性错误: 'Tensor' object has no attribute 'numpy' in Tensorflow 2. 1