问题
我需要测试列中每个数字的第一个数字以了解条件.
条件
是checkVar的第一个数字大于5或者是checkVar的第一个数字小于2
然后设置newVar = 1
解
有人认为我曾经将其转换为字符串,留下空格,然后取[0],但我无法弄清楚代码.
也许是这样的,
df.ix[df.checkVar.str[0:1].str.contains('1'),'newVar']=1
Run Code Online (Sandbox Code Playgroud)
这不是我想要的,由于某种原因我得到了这个错误
invalid index to scalar variable.
Run Code Online (Sandbox Code Playgroud)
测试我的原始变量我得到的值应符合条件
df.checkVar.value_counts()
301 62
1 15
2 5
999 3
dtype: int64
Run Code Online (Sandbox Code Playgroud)
理想情况下,它看起来像这样:
checkVar newVar
NaN 1 nan
2 nan
3 nan
4 nan
5 301.0
6 301.0
7 301.0
8 301.0
9 301.0
10 301.0
11 301.0
12 301.0
13 301.0
14 1.0 1
15 1.0 1
Run Code Online (Sandbox Code Playgroud)
更新
我的最终解决方案,因为实际问题更复杂
w = df.EligibilityStatusSP3.dropna().astype(str).str[0].astype(int)
v = df.EligibilityStatusSP2.dropna().astype(str).str[0].astype(int)
u = df.EligibilityStatusSP1.dropna().astype(str).str[0].astype(int)
t = df.EligibilityStatus.dropna().astype(str).str[0].astype(int) #get a series of the first digits of non-nan numbers
df['MCelig'] = ((t < 5)|(t == 9)|(u < 5)|(v < 5)|(w < 5)).astype(int)
df.MCelig = df.MCelig.fillna(0)
Run Code Online (Sandbox Code Playgroud)
t = df.checkVar.dropna().astype(str).str[0].astype(int) #get a series of the first digits of non-nan numbers
df['newVar'] = ((t > 5) | (t < 2)).astype(int)
df.newVar = df.newVar.fillna(0)
Run Code Online (Sandbox Code Playgroud)
这可能会稍微好一些,不确定,但另一种非常类似的方式来接近它.
t = df.checkVar.dropna().astype(str).str[0].astype(int)
df['newVar'] = 0
df.newVar.update(((t > 5) | (t < 2)).astype(int))
Run Code Online (Sandbox Code Playgroud)