【问题标题】:Normalize columns in pandas dataframe规范化熊猫数据框中的列
【发布时间】:2020-10-21 03:30:22
【问题描述】:

我有一个 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 Books )。我已经查看了有关如何缩放单个列的示例,例如 Chris Albon,并且我在这里看到了用于缩放 all 列的示例,但是每次我尝试将此数据帧转换为数组来缩放,事情令人窒息,因为术语列不是数字。 (我尝试将术语列设置为索引,但这并不顺利。)我可以想象一种使用for 循环的方法,但几乎每个干净的 pandas 代码示例我read 说不要使用 for 循环,因为有一种 pandas 方式来做所有事情。

我想要的是某种说法:

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

就是这样。

【问题讨论】:

  • 你想要一列还是多列
  • 这能回答你的问题吗? Normalize columns of pandas data frame
  • 谢谢,@RajuBhaya。实际上,我查看了那个答案,但它没有显示从预处理中排除非数字列的方法,而且您可能知道,numpy 数组不喜欢文本! (在我提出上述问题的过程中,我什至尝试了那个特定的代码示例!)

标签: python pandas normalization


【解决方案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

【讨论】:

  • 感谢两位的精彩回答。这个被检查为最简单和最像熊猫的。 (或者“pythonic”的熊猫等价物是什么。
【解决方案2】:

试试这个:

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

【讨论】:

  • 再次感谢您的回答。虽然我给另一个答案是我决定使用的检查,但我会记住这个对 lambda 函数的使用。
猜你喜欢
  • 2014-12-12
  • 1970-01-01
  • 2017-05-04
  • 2021-04-11
  • 1970-01-01
  • 1970-01-01
  • 2015-04-19
  • 2018-10-06
  • 2017-07-10
相关资源
最近更新 更多