规范熊猫数据框中的列

时间:2020-06-30 18:34:16

标签: python pandas normalization

我有一个pandas数据框,它的术语语料库频率是行,年份是列,像这样:

|       | term    |   2002 |   2003 |   2004 |   2005 |
|------:|:--------|-------:|-------:|-------:|-------:|
|  3708 | climate |      1 |     10 |      1 |     14 |
|  8518 | global  |     12 |     11 |      2 |     12 |
| 13276 | nuclear |     10 |      1 |      0 |      4 |

我希望能够通过将每个单词的值除以给定年份的单词总数来规范化每个单词的值-某些年份包含的文本数量是原来的两倍,因此我尝试按年份缩放(例如Google图书) )。我看过如何缩放单个列的示例,例如Chris Albon,我在SO上也看到过用于缩放 all 列的示例,但是每次我尝试将此数据帧转换为一个数组按比例缩放,这使术语列不是数字这一事实感到困扰。 (我尝试将terms列设置为索引,但是效果并不理想。)我可以想象一种通过for循环执行此操作的方法,但是几乎每个干净的 pandas 例子我读过的代码说不要使用循环,因为有一种熊猫的方式,一切都很好。

我想说的是一种方式:

for these columns [the years]:
    divide each row by the sum of all rows

就是这样。

2 个答案:

答案 0 :(得分:1)

尝试一下:

import pandas as pd

df = pd.DataFrame(
    columns=['term', '2002', '2003', '2004', '2005'],
    data=[['climate', 1, 10, 1, 14],
          ['global', 12, 11, 2, 12],
          ['nuclear', 10, 1, 0, 4], ])
normalized = df.select_dtypes('int').apply(lambda x: x / sum(x))
df = df.merge(
    right=normalized,
    left_index=True,
    right_index=True,
    suffixes=['', '_norm']
)

返回

      term  2002  2003  2004  2005  2002_norm  2003_norm  2004_norm  2005_norm
0  climate     1    10     1    14   0.043478   0.454545   0.333333   0.466667
1   global    12    11     2    12   0.521739   0.500000   0.666667   0.400000
2  nuclear    10     1     0     4   0.434783   0.045455   0.000000   0.133333

答案 1 :(得分:1)

尝试:

In [5]: %paste                                                                                                                                                                                                                                                                       
cols = ['2002', '2003', '2004', '2005']
df[cols] = df[cols] / df[cols].sum()

## -- End pasted text --

In [6]: df                                                                                                                                                                                                                                                                           
Out[6]: 
      term      2002      2003      2004      2005
0  climate  0.043478  0.454545  0.333333  0.466667
1   global  0.521739  0.500000  0.666667  0.400000
2  nuclear  0.434783  0.045455  0.000000  0.133333