熊猫索引if语句

时间:2018-10-06 11:07:51

标签: python pandas dataframe

如果索引大于pandas数据帧中的x,我尝试创建一个新的1列。

但是此代码不起作用。有人有什么想法吗?

<div class="container">
  <div class="row">
     <div class="column" style="background-color:#bbb;">
        <h2>Column 1</h2>
        <p>Some text..</p>
     </div>
     <div class="column" style="background-color:#aaa;">
        <h2>Column 2</h2>
        <p>Some text..</p>
     </div>
     <div class="column" style="background-color:#bbb;">
        <h2>Column 3</h2>
        <p>Some text..</p>
     </div>
     <div class="column" style="background-color:#aaa;">
        <h2>Column 4</h2>
        <p>Some text..</p>
     </div>
     <div class="column" style="background-color:#bbb;">
        <h2>Column 1</h2>
        <p>Some text..</p>
     </div>
     <div class="column" style="background-color:#aaa;">
        <h2>Column 2</h2>
        <p>Some text..</p>
     </div>
     <div class="column" style="background-color:#bbb;">
        <h2>Column 3</h2>
        <p>Some text..</p>
     </div>
     <div class="column" style="background-color:#aaa;">
        <h2>Column 4</h2>
        <p>Some text..</p>
     </div>
   </div>
   <div class="row">
     <div class="column" style="background-color:#bbb;">
        <h2>Column 1</h2>
        <p>Some text..</p>
     </div>
     <div class="column" style="background-color:#aaa;">
        <h2>Column 2</h2>
        <p>Some text..</p>
     </div>
     <div class="column" style="background-color:#bbb;">
        <h2>Column 3</h2>
        <p>Some text..</p>
     </div>
     <div class="column" style="background-color:#aaa;">
        <h2>Column 4</h2>
        <p>Some text..</p>
     </div>
     <div class="column" style="background-color:#bbb;">
        <h2>Column 1</h2>
        <p>Some text..</p>
     </div>
     <div class="column" style="background-color:#aaa;">
        <h2>Column 2</h2>
        <p>Some text..</p>
     </div>
     <div class="column" style="background-color:#bbb;">
        <h2>Column 3</h2>
        <p>Some text..</p>
     </div>
     <div class="column" style="background-color:#aaa;">
        <h2>Column 4</h2>
        <p>Some text..</p>
     </div>
   </div>
</div>

1 个答案:

答案 0 :(得分:3)

以下面的示例dataframe为例

df  = pd.DataFrame({"a":[1,2,3,4,5],"b":[2,4,9,16,25]})

索引方法打印如下

In [4]: df.index
Out[4]: RangeIndex(start=0, stop=5, step=1)

df.index >3打印如下

In [5]: df.index>3
Out[5]: array([False, False, False, False,  True])

所以答案是

y = df.index>3
df['new_column'] = y.astype(int)
df
   a   b  new_column
0  1   2    0
1  2   4    0
2  3   9    0
3  4  16    0
4  5  25    1

编辑: 如果您想做3到9个索引 您执行以下操作

import numpy as np
np.logical_and(df.index>2, df.index<5)
array([False, False, False,  True,  True])