I am working on data that has values in index column and I need additional columns for filtering.
Here is an example of my data:
PERIOD BUDGET
B156789 MY First 202201 2829,09
B156456 My Second 202203 78,98
B156324 Third 202204 82,98
B156098 Fourth 202207 9292,26
I would like to add new column after index with name PROJECT and as an output:
PROJECT PERIOD BUDGET
B156789 MY First B156789 202201 2829,09
B156456 My Second B156456 202203 78,98
B156324 Third B156324 202204 82,98
B156098 Fourth B156098 202207 9292,26
Split should be performed with?:
stripped = text.split()[0]
For adding new column I have tried below, but in this case index column does not have a name, so following is not working:
df = df.eval('PROJECT=B', inplace=True)
CodePudding user response:
You can try
df['PROJECT'] = df.index.str.split().str[0]
print(df)
PERIOD BUDGET PROJECT
B156789 MY First 202201 2829,09 B156789
B156456 My Second 202203 78,98 B156456
B156324 Third 202204 82,98 B156324
B156098 Fourth 202207 9292,26 B156098
To set it into first column
df.insert(0, 'PROJECT', df.index.str.split().str[0])
print(df)
PROJECT PERIOD BUDGET
B156789 MY First B156789 202201 2829,09
B156456 My Second B156456 202203 78,98
B156324 Third B156324 202204 82,98
B156098 Fourth B156098 202207 9292,26