0

i have pandas dataframe where the row is [“a” “b”]. how I can convert it into the comma separated list like [“a”, “b”]?

I’m expecting to get back list with two comma separated elements

  • 1
    What's the output `df.head(5).to_dict()`? – Ynjxsjmh Mar 03 '23 at 05:01
  • 1
    Where are you reading that dataFrame from, Can you give any sample data? – Manoj biroj Mar 03 '23 at 05:30
  • 1
    "Space separated list" and "comma separated list" aren't things in Python. All lists are displayed with comma separators. Is the input actually a string? Also, the output you're showing has curly quotes, which aren't valid in Python. Please [edit] to clarify. See [mre] and [How to make good reproducible pandas examples](/q/20109391/4518341) – wjandrea Mar 03 '23 at 05:47

1 Answers1

0

If your column contains string like ["a" "b"], you can use str.findall to convert them as real list or str.replace to replace ' ' by ', ':

df = pd.DataFrame({'col1': ['["a" "b"]']})

df['col2'] = df['col1'].str.findall(r'"([^"]+)"')

df['col3'] = df['col1'].str.replace(r'"(\s+)"', '", "', regex=True)

Output:

>>> df
        col1        col3    col2
0  ["a" "b"]  ["a", "b"]  [a, b]
Corralien
  • 109,409
  • 8
  • 28
  • 52