简体   繁体   English

使用 pandas dataframe 将值替换为某些起始字符串索引

[英]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".基本上,如果我的列 DISCREP 中的某些内容等于字符串“True”,它会将“数字”列中的值更改为 1200。是否有 select 的方法并根据某些参数更改多个表值,例如“全部'discrep' 列中以 'HY' 开头的值,会将 'number' 列中的值更改为 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' .在这里你可以使用这个df1['DISCREP'].str.startswith('HY')而不是df1.DISCREP=='True'因为第一个代码示例将生成一个 boolean 掩码,它将True放入以开头的字符串'HY'

Sample of a boolean mask: boolean 掩码示例:

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

Hope it helped!希望它有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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