使用.loc循环并在if中传递条件

时间:2018-12-16 15:30:06

标签: python pandas

我有一个包含2列的DataFrame-like(id:string,l:string){ if(l == 1){this.likes=0 }else{this.likes=1}; this.gs.like(id,this.likes).subscribe( (data)=>{ console.log(data); this._router.navigate(["/routeurl"]) } ); } len。数据如下: dummy data

如果agr的值为7,我想从agr中切出一部分。这是相同代码段:

len

但是我遇到错误:

for i in range(len(df)):
    print (i)

    if df.loc(i,'len')==7:
        print ("if",i)
        df['agr1'] = df.agr.str.slice(3,5)
        df['agr2'] = df.agr.str.slice(1,2)    
    else:
        print ("else",i)
        df['agr1'] = df.agr.str.slice(4)
        df['agrt2'] = df.agr.str.slice(3,6)

1 个答案:

答案 0 :(得分:0)

您的TypeError是因为.loc带括号,例如.loc[i, j],而不是.loc(i, j)

import pandas as pd
import numpy as np

# Make new columns and fill them with nulls
df['agr1'] = np.nan
df['agr2'] = np.nan

# Find all the rows where len is 7
df_idx = df['len'] == 7 

# Set agr1 and agr2 where len is 7 
df.loc[df_idx, 'agr1'] = df.loc[df_idx, 'agr'].str.slice(4)
df.loc[df_idx, 'agr2'] = df.loc[df_idx, 'agr'].str.slice(3,6)

# Set agr1 and agr2 where len isn't 7
df.loc[~df_idx, 'agr1'] = df.loc[~df_idx, 'agr'].str.slice(3,5)
df.loc[`df_idx, 'agr2'] = df.loc[~df_idx, 'agr'].str.slice(1,2)

和往常一样,没有任何数据,我不知道这是您要执行的操作还是错误(或损坏)。