具有条件规则的Pandas Dataframe

时间:2017-07-22 16:20:08

标签: python pandas dataframe

我有以下数据框

import pandas as pd
df= pd.DataFrame({'Name':['Tam','John','Tom','Mark','Tim'],'Surname':['Jones','James','James','Perez','Desouza'],'ID':['-','-','-','-','-'],'ID1':['-','-','-','-','-']})

df.loc[df.Name.str.startswith('T'),'ID']="Rule 1"
df.loc[df.Surname.str.startswith('J'),'ID1']="Rule 2"

"规则2"仅当ID列已经具有" - "以外的值时才会在ID1中填充。 - "。

我正在努力通过首先测试ID是否填充了值来最有效地在ID1列中应用规则2。

1 个答案:

答案 0 :(得分:1)

我认为您可以使用&(按位和)链接新条件,不要忘记()

df.loc[df.Name.str.startswith('T'),'ID']="Rule 1"
df.loc[df.Surname.str.startswith('J') & (df.ID != '-'),'ID1']="Rule 2"
print (df)
       ID     ID1  Name  Surname
0  Rule 1  Rule 2   Tam    Jones
1       -       -  John    James
2  Rule 1  Rule 2   Tom    James
3       -       -  Mark    Perez
4  Rule 1       -   Tim  Desouza

或者:

df.loc[df.Name.str.startswith('T'),'ID']="Rule 1"
df.loc[df.Surname.str.startswith('J') & df.Name.str.startswith('T'),'ID1']="Rule 2"
print (df)
       ID     ID1  Name  Surname
0  Rule 1  Rule 2   Tam    Jones
1       -       -  John    James
2  Rule 1  Rule 2   Tom    James
3       -       -  Mark    Perez
4  Rule 1       -   Tim  Desouza