I have dataframe which consists two columns text column and server column, In text column i have to remove square brackets based on server column condition i.e.,[where server column == DEV].
Input Dataframe
Text Column Server Column
['java error:404 URL not found'] DEV
['java error:500 internal server'] DEV
HTTP status 204 (No Content) PROD
HTTP status 200 created successfully PROD
Output Dataframe
Text Column Server Column
'java error:404 URL not found' DEV
'java error:500 internal server' DEV
HTTP status 204 (No Content) PROD
HTTP status 200 created successfully PROD
####################################################
I tried with below code but not working
data =data[data['server']== 'DEV']
data =data["nodes"].apply(lambda x: ",".join(x) if isinstance(x, list) else x) print(data)
But above code snippet is not working
CodePudding user response:
If your column contains real list, you can use:
df['Text Column'] = df['Text Column'].mask(df['Text Column'].str.len() > 1) \
.str[0].fillna(df['Text Column'])
print(df)
# Output
Text Column Server Column
0 java error:404 URL not found DEV
1 java error:500 internal server DEV
2 HTTP status 204 (No Content) PROD
3 HTTP status 200 created successfully PROD
CodePudding user response:
Assuming that df is your DataFrame, this task can be done as follow.
dev_text = df[df['Server Column'] == 'DEV']['Text Column']
dev_text = dev_text.str.replace('[', repl = '', regex = False).str.replace(']', repl = '', regex = False)
df.loc[df['Server Column'] == 'DEV', 'Text Column'] = dev_text.values