简体   繁体   English

如果一行包含特定字符串,pandas 是否可以在新列中创建一个整数

[英]Is there a way in pandas to create an integer in a new column if a row contains a specific string

For example, I have the following dataframe:例如,我有以下数据框:

初始数据帧

I want to transform the dataframe from above to something like this:我想将数据框从上面转换为这样的:

在此处输入图片说明

Thank's for any kind of help!感谢您提供任何帮助!

跑:

df['Number'] = df.svn_changes.str.match(r'r\d+').cumsum()

Yes, is contains with regex and cumsum :是的, contains正则表达式和cumsum

df = pd.DataFrame({'svn_changes':['r123456','RowValueRow','ValueRowValue',
                                  'some_string_string','r234566','ValueRowValue',
                                  'some_string_string','r123789','something_here',
                                  'ValueRowValue','String_2','String_4']})

df['Number'] = df['svn_changes'].str.contains('r\d+').cumsum()
print(df)

Output:输出:

           svn_changes  Number
0              r123456       1
1          RowValueRow       1
2        ValueRowValue       1
3   some_string_string       1
4              r234566       2
5        ValueRowValue       2
6   some_string_string       2
7              r123789       3
8       something_here       3
9        ValueRowValue       3
10            String_2       3
11            String_4       3

Here's a simple reusable line you can use to do that:这是一个简单的可重复使用的行,您可以使用它来做到这一点:

df['new_col'] = df['old_col'].str.contains('string_to_match')*1

The new column will have value 1 if the string is present in this column, and 0 otherwise.如果该列中存在字符串,则新列的值为1 ,否则为0

暂无
暂无

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

相关问题 如果 DataFrame 包含特定字符串,则创建新列 - Create new column if DataFrame contains specific string 复制包含行上的字符串并将特定结果移动到新列 Pandas python - Replicate contains string on row and move with specific result to new column Pandas python 移动行值包含特定字符串到 Python 中的新列 - Moving row values contains specific string to new column in Python 使用 pandas 字符串包含和循环创建新类别列 - create new category column using pandas string contains and loops 在特定行和列熊猫的文本开头分配新字符串 - Assign new string in the beginning of a text in a specific row and column pandas Pandas - 检查行是否包含特定字符串并在新列中返回结果 - Pandas - Check if row contain specific string and return result in a new column pandas:在列包含特定值的行之后插入一行 - pandas: insert a row after a row where the column contains a specific value 如何从 pandas 中括号中包含特定列名称的行创建新列 - how to create a new column from a row containing specific column name in brackets in pandas 如果字符串“包含”子字符串,则创建一个带有条件的新列? - Create a new column with condition if a string 'contains' substring? 如果列包含列表中的字符串,则如何/在 df 中创建新列的最佳方法对两者都使用小写 - How to / Best way to create a new column in a df if a column contains string from a list using lower casing for both
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM