I have a dataframe df :-
| Type |
|---|
| 9F,5F/6F,3T,1T |
| 18F/19F,2F,9T,4T |
| 17F/12F |
| 3T |
| No Types |
I want to generate these two additional columns based on Type column ,All wordsending with Fs seperated in one and all Ts seperated in another column respectively.If Type is No Types then No Types in both the columns:-
| Type | Fcol | Tcol |
|---|---|---|
| 9F,5F/6F,3T,1T | 9F,5F/6F | 3T,1T |
| 18F/19F,2F,9T,4T | 18F/19F,2F | 9T,4T |
| 17F/12F | 17F/12F | Absent |
| 3T | Absent | 3T |
| No Types | No Types | No Types |
>Solution :
I would use str.extract and a regex:
# extract F and T parts
df2 = df['Type'].str.extract('(.*\dF)?,?(\d+T.*)?')
df[['Fcol', 'Tcol']] = df2.fillna('Absent')
# identify no F nor T
m = df2.isna().all(axis=1)
# and fill original values for those
df.loc[m, ['Fcol', 'Tcol']] = df.loc[m, 'Type']
Output:
Type Fcol Tcol
0 9F,5F/6F,3T,1T 9F,5F/6F 3T,1T
1 18F/19F,2F,9T,4T 18F/19F,2F 9T,4T
2 17F/12F 17F/12F Absent
3 3T Absent 3T
4 No Types No Types No Types