I have somethinghs like:
df1 = pd.DataFrame({'Name' : ['Jake', 'Nate', 'Max', 'Alex', 'Lex', 'Kat', 'Nate', 'Jake'],
'textBefore F1: textAfter' : [1, 2, 3, 4, 5, 6, 7, 8],
'textBefore F2: textAfter' : [8, 4, 2, 7, 9, 6, 5, 1],
'textBefore F3: textAfter' : [9, 8, 5, 4, 6, 3, 2, 5],
'Color' : ['red', 'blue', 'yellow', 'balck', 'purple', 'pink', 'orange', 'green'],})
I would like to rename only the columns that contain the 'F'. And I would like to keep the number that follows the F. For example:
textBefore F1: textAfter
he should become alone
F1
Of course for each line that contains the F. How could I do?
CodePudding user response:
Lets use index.str.replace
df1.columns = df1.columns.str.replace(r'.*\b(F\d )\b.*', r'\1', regex=True)
Result
Name F1 F2 F3 Color
0 Jake 1 8 9 red
1 Nate 2 4 8 blue
2 Max 3 2 5 yellow
3 Alex 4 7 4 balck
4 Lex 5 9 6 purple
5 Kat 6 6 3 pink
6 Nate 7 5 2 orange
7 Jake 8 1 5 green