简体   繁体   English

如何在dataframe列中的某些字符后提取整个字符串部分?

[英]How to extract entire part of string after certain character in dataframe column?

I am working on using the below code to extract the last number of pandas dataframe column name. 我正在使用下面的代码来提取最后一个pandas dataframe列名。

names = df.columns.values
new_df = pd.DataFrame()
for name in names:    
    if ('.value.' in name) and df[name][0]:
        last_number = int(name[-1])
        print(last_number)
        key, value = my_dict[last_number]
        try:
            new_df[value][0] = list(new_df[value][0]) + [key]
        except:
            new_df[value] = [key]

name is a string that looks like this: name是一个如下所示的字符串:

'data.answers.1234567890.value.0987654321'

I want to take the entire number after .value. 我想在.value.之后取整个数字.value. as in the IF statement. 如在IF声明中。 How would do this in the IF statement above? 在上面的IF语句中如何做到这一点?

Use str.split , and extract the last slice with -1 (also gracefully handles false cases): 使用str.split ,并使用-1提取最后一个切片(也正常处理错误情况):

df = pd.DataFrame(columns=[
    'data.answers.1234567890.value.0987654321', 'blahblah.value.12345', 'foo'])    

df.columns = df.columns.str.split('value.').str[-1]
df.columns
# Index(['0987654321', '12345', 'foo'], dtype='object')

Another alternative is splitting inside a listcomp: 另一种方法是在listcomp中拆分:

df.columns = [x.split('value.')[-1] for x in df.columns]
df.columns
# Index(['0987654321', '12345', 'foo'], dtype='object')

暂无
暂无

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

相关问题 如何提取 python 列 dataframe 上的特殊字符之间的字符串? - How to extract a string between special character on a column dataframe in python? 在某个字符后从字符串中提取数字 - Extract a number from a string, after a certain character 如果Python以数据帧中的某些字符开头,则替换整个字符串 - Python replace entire string if it begin with certain character in dataframe 如何在数据框列中的字符之后删除字符串的其余部分? - How do I remove the rest of a string after a character in a dataframe column? 从字符串中提取 substring 并应用于整个 dataframe 列 - Extract substring from string and apply to entire dataframe column Pandas 从 dataframe 中的列中提取部分字符串并将其存储在新列中 - Pandas extract part of string form a column in a dataframe and store it in a new column 从pandas数据帧中的整列中删除某些字符串 - Remove certain string from entire column in pandas dataframe 如何在熊猫数据框单元格中提取部分字符串并在其中创建一个包含该字符串的新列 - How to extract part of a string in pandas dataframe cell and create a new column with that string inside it 如何使用列索引删除第一列中以特定字符串开头的 Dataframe 行 - How to drop Dataframe rows that start with a certain character string in the first column using column index 使用pandas在关键短语之后提取字符串的特定部分? - Extract a certain part of a string after a key phrase using pandas?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM