【问题标题】:Vectorized looping pandas矢量化循环熊猫
【发布时间】:2020-10-02 13:17:50
【问题描述】:

您好,我需要根据特定条件创建一个值为 1 或 0 的列。我的数据框很大,所以一般的 for 循环甚至应用都非常慢。我想使用 Pandas,甚至更喜欢 Numpy 矢量化。以下是数据示例和我的代码不起作用:

election_year     D_president

1992                 0
1992                 0
1996                 0
1996                 0
2000                 0
2004                 0
2008                 0
2012                 0
test_df['D_president'] = 0
election_year = test_df['election_year']
test_df['D_president'] = test_df.loc[((election_year == 1992) | 
(election_year == 1996) | 
(election_year == 2008)| 
(election_year == 2012)), 'D_president'] = 1

所以基本上我需要在这些特定年份的“D_president”列中获得值 1。但是,当我执行此代码时,即使是 2000 年和 2004 年,我也会得到全部 1。无法理解出了什么问题。 另外,我如何将其转换为带有 .values 的 Numpy 矢量化?

【问题讨论】:

  • 看起来您在同一行上有两个“=”分配。尝试删除最左边的 test_df['D_president'] 另外,对于测试,您可以将其替换为election_year.isin([1992, 1996, 2008, 2012]))
  • @ilmarinen 谢谢!作品!!想要添加答案?我会标记的。

标签: python pandas loops vectorization


【解决方案1】:

您在同一行上似乎有两个“=”分配。尝试删除最左边的 test_df['D_president'] 另外,对于测试,您可以将其替换为election_year.isin([1992, 1996, 2008, 2012]))

【讨论】:

    猜你喜欢
    • 2015-11-01
    • 2021-09-12
    • 2016-05-02
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 2012-09-24
    • 2022-01-02
    相关资源
    最近更新 更多