0

I am creating a data table with an assortment of columns and values. At times, if a column value is equal to a certain value, I wish to change another value in a different column. An example is listed below.

df1.loc[df1.DISCREP=='True','Number'] = 1200

Basically, if something in my column DISCREP equals the string "True", it'll change the value in the 'Number' Column to 1200. Is there a method to select and change multiple table values based on certain parameters, such as "All values in 'discrep' column starting with 'HY', will change the values in the 'number' column to 0". This also applies to values that also may be in different uppercase or lowercase order.

Sorry if this wording is a little confusing, any help would be appreciated

dom ryan
  • 27
  • 4
  • 1
    There are many `.str` methods (e.g. ,`.str.contains`, `.str.startswith`) that you can match on whether they `contain` some substrings, and those methods also have a `case` argument so that you can match regardless of case. – ALollz Jan 06 '22 at 21:02
  • What would the syntax for that look like? – dom ryan Jan 06 '22 at 21:09
  • The solution here should give you the syntax: https://stackoverflow.com/questions/17957890/pandas-select-from-dataframe-using-startswith. So you'd have something like: `df1.loc[df1.DISCREP.startswith('HY', case=False, na=False), 'Number'] = 1200` – ALollz Jan 06 '22 at 21:10

1 Answers1

0

here you can use this df1['DISCREP'].str.startswith('HY') instead of df1.DISCREP=='True' because the first code sample will generate a boolean mask that will put True to the strings which begin with 'HY'.

Sample of a boolean mask :

0         True
1         True
2         True
3         True
4         True
         ...  
24565    False
24566    False
24567    False
24568    False
24569    False

Hope it helped!

rafidini
  • 216
  • 1
  • 8