矢量化循环 pandas

Vectorized looping pandas

您好,我需要根据特定条件创建一个值为 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]))