简体   繁体   中英

Using pandas dataframe to replace values with certain starting string indices

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM