This is likely a very obvious question, but I have a column containing lists that I am trying to flatten: i.e [AB, CD] -> AB, CD.
Sample dataframe:
data = [
["ABC", ["AB", "AB", "EF"]],
["DEF", ["CD", "EF"]],
["GHI", ["JK"]],
[
"JKL",
np.nan,
],
]
df = pd.DataFrame(data, columns=["ID", "list"])
df
I am applying this function to said column:
def func(string):
flattened_string = ", ".join(map(str, string))
return flattened_string
df = df["list_column"].apply(func)
However there are a few rows containing NaN values that initiate the error "TypeError: 'float' object is not iterable". Is there any way I can modify this function to fix this? Or perhaps (likely) a much better way to do this?
Thank you!!!