python - 使用 Pandas 检查列的第一位数字

标签 python pandas

问题
我需要测试列中每个数字的第一个数字的条件。

条件
是 checkVar 的第一个数字大于 5 或者 是 checkVar 的第一个数字小于 2
然后设置newVar=1

解决方案

有人以为我已经将它转换成一个字符串,去掉空格,然后取 [0],但我想不出代码。

也许是这样的,

df.ix[df.checkVar.str[0:1].str.contains('1'),'newVar']=1

这不是我想要的,出于某种原因我得到了这个错误

invalid index to scalar variable.

测试我的原始变量我得到应该满足条件的值

df.checkVar.value_counts()
301    62
1      15
2       5
999     3
dtype: int64   

理想情况下它看起来像这样:

            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

更新
我的最终解决方案,因为实际问题更复杂

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)

最佳答案

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)

这可能稍微好一点,不确定,但是另一种非常相似的方法。

t = df.checkVar.dropna().astype(str).str[0].astype(int)
df['newVar'] = 0
df.newVar.update(((t > 5) | (t < 2)).astype(int))

关于python - 使用 Pandas 检查列的第一位数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27810417/

相关文章:

python - 我可以关闭隐式 Python unicode 转换来查找我的混合字符串错误吗?

python Selenium : Get dynamic update of text of an element

python - 在南方,我可以将旧列的值复制到新列吗?

python super 执行父方法

python - 正则表达式:将 "white space"字符和 - 字符更改为空

python - 我们可以有更快的方法来创建数组吗?

python - Numpy 按多个向量分组,获取组索引

python - 如果两列具有不同的值,则删除连续的 2 行 [Panda]

python - 让 x 轴网格显示在 matplotlib 中

python - groupby之后,如何展平列标题?