I have a column called 'Timestamp' in dataframe. It has values in the form of lists joined by comma. I want to combine these different lists into single list. I am able to replace single character, but I am getting error when I do it as a whole how can I do this?
Example: 1 value of 1 row of column is ['2021-10-03 05:29:39.199'],['2021-10-03 06:58:55.584'] I am not able to create dataframe for this value.
Code I am using is
inputData["Timestamp"] = inputData["Timestamp"].str.replace('],[', ',')
But I am getting error.
How to solve this?
CodePudding user response:
One approach would be to use ast.literal_eval
which can safely evaluate an string containing a Python
expression.. With your current format it returns a tuple of lists.
>>> import ast
>>> ast.literal_eval("['time1'], ['time2']")
(['time1'], ['time2'])
So you can apply this function across your Timestamp
column.
inputData["Timestamp"] = inputData["Timestamp"].apply(lambda x: [t[0] for t in ast.literal_eval(x)])
CodePudding user response:
Maybe this will solve your problem:
str.replace(r"'],['" , ',')
Use this instead of your code:
inputData["Timestamp"] = inputData["Timestamp"].str.replace(r"'],['" , ',')