0

In table A, there’s columns 1 and 2.

  • Column 1 is unique id’s like (‘A12324’) and column 2 is blank for now.
  • I want to fill the value of column 2 with Yes if the id starts with A, and else No.

Is any one familiar with how I can maybe use a left for this?

I tried this but my error read that left is not defined.

 TableA.loc[TableA['col1'] == left('A',1), 'hasAnA'] = 'Yes'
petezurich
  • 9,280
  • 9
  • 43
  • 57
Lauren
  • 23
  • 3

1 Answers1

0

You can use the pd.Series.str.startswith() method:

>>> frame = pd.DataFrame({'colA': ['A12342', 'B123123231'], 'colB': False})
>>> condition = frame['colA'].str.startswith('A')
>>> frame.loc[condition, 'colB'] = 'Yes'
>>> frame
         colA  colB
0      A12342   Yes
1  B123123231  False
johannesack
  • 660
  • 3
  • 19
  • What if I wanted to add multiple conditions? like 'colA' starts with A, 'colA' ends with B, and 1 more? I'm attempting 3 conditions using your method and it is unsuccessful. – Lauren Feb 26 '20 at 19:23
  • @Lauren You can define multiple conditions similarly to the condition in the code example, and then combine them by using the `&` operator: `combined_cond = condA & condB & condC` – johannesack Feb 26 '20 at 22:22
  • I did that like so and got an error about my syntax right at the and. 'Condition = ((df['status']=='Live') and (df['name'].str.startswith('A') and (df['true']==1)) df.loc[Condition, 'EmptyCol'] = 'True' ' – Lauren Feb 26 '20 at 22:36
  • You have to use `&`, not `and` – johannesack Feb 28 '20 at 17:21