【问题标题】:Creating a variable based on the values of two other variables根据其他两个变量的值创建一个变量
【发布时间】:2020-01-12 14:41:37
【问题描述】:

我在 pandas 中有一个数据框,其中包含两个变量:DEC 和 TYPE

dec     type
 1        13
 2        2
 2        5
 2        7
 2        9
 3        5

从这两个变量中,我想根据这两个变量的值创建其他二进制变量。

我无法找到代码来准确地编写我想要的代码,但是在 python-English 中,它会是这样的:

df['new_variable'] = 1 if DEC == 1 & TYPE == 3 or 2 or 1

如果我可以在我的问题中包含一些内容来澄清我在寻找什么,请告诉我。

从答案更新:

我遇到了一个问题,因为对于每个变量,我需要运行两行代码(如下),当我运行第二行时,它会超出第一行中的编码。如何同时运行两行(即第二行不超过第一行)?

harrington_citations['gov_winner'] =  np.where((harrington_citations['dec'] == 1) & harrington_citations['type'].isin([1,2,3,4,22]) , 1, 0)

harrington_citations['gov_winner'] = np.where((harrington_citations['dec'] == 2) & harrington_citations['type'].isin([1,5,9,13,18]), 1, 0)

【问题讨论】:

  • or (V) 2 or (V) 1 是什么意思? V 定义在哪里?
  • 它既不是 Python 也不是英语。你能解释一下条件是什么吗?

标签: python pandas dataframe variables


【解决方案1】:

看起来您需要 .isin 来满足第二个条件并返回 1/0:

df['new_variable'] = (df['dec'].eq(1) & df['type'].isin([3,2,1])).view('i1')

按 cmets 编辑,您应该使用| comdition 创建 2 个条件:

c1 = (harrington_citations['dec'] == 1) & harrington_citations['type'].isin([1,2,3,4,22])
c2 = (harrington_citations['dec'] == 2) & harrington_citations['type'].isin([1,5,9,13,18])
harrington_citations['gov_winner'] = (c1|c2).view('i1')

【讨论】:

  • 出现了一个问题,因为值需要编码两次...请查看我对问题的编辑。
  • @GrahamStreich 已编辑答案,请检查
【解决方案2】:

np.nan 替换为适合您的任何值:

df['new_variable'] = np.where((df['dec'] == 1) & df['type'].isin([1,2,3]), 1, np.nan)

【讨论】:

  • 最后两个参数“1”和“np.nan”指定了什么?分别满足条件时的值和不满足条件时的值?试图通过这个文档弄清楚:docs.scipy.org/doc/numpy/reference/generated/numpy.where.html
  • 你说得对。您可以将它们指定为答案中的标量或数组
  • 出现了一个问题,因为值需要编码两次...请查看我对问题的编辑。