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

Viewed 11682

I am working on using the below code to extract the last number of pandas dataframe column name.

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:

'data.answers.1234567890.value.0987654321'

I want to take the entire number after .value. as in the IF statement. How would do this in the IF statement above?

1 Answers

Use str.split, and extract the last slice with -1 (also gracefully handles false cases):

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:

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