I have a pandas dataframe where one column RESULT has list inside a list.
ID RESULT
0 A [nan, ['PASS'], nan, nan]
1 B [['FAIL'], nan, nan, nan]
2 C [['PASS'], nan, nan, nan]
3 D [nan, nan, nan, nan]
4 E [nan, ['FAIL'], nan, nan]
I want to make the RESULT column a flat list. For example the first case would be [nan, 'PASS', nan, nan]. Final answer should look like below.
ID RESULT
0 A [nan, 'PASS', nan, nan]
1 B ['FAIL', nan, nan, nan]
2 C ['PASS', nan, nan, nan]
3 D [nan, nan, nan, nan]
4 E [nan, 'FAIL', nan, nan]
I tried to create a function but it is not updating the column to a flat list. Below is the code I tried.
def flatten_list(mylist):
# print(mylist)
for index, value in enumerate(mylist):
if type(value) is list:
mylist[index] = value[0]
# print(mylist)
return mylist
df_bin['RESULT'] = df_bin['RESULT'].apply(flatten_list)
But if I try a simple example below it works. I wonder what is the difference. I will appreciate any guidance. Also is it possible to use lambda function to achieve the same result.
mylist = [nan, ['PASS'], nan, nan]
for n, i in enumerate(mylist):
if type(i) is list:
mylist[n] = i[0]
print(mylist)