【发布时间】: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