'Coverting string to dataframe python [duplicate]

I have a data like the below. How can I convert this string data to pandas dataframe?

data='"customer_id"|"first_name"|"city_name"\r\n123456"|"ABC"|"ARGENTINA"\r\n"2000142707"|"efgh"|"LOMELLO"\r\n


Solution 1:[1]

Just use pd.read_csv, and specify sep="|"

from io import StringIO
df = pd.read_csv(StringIO(data), sep='|')

Of course, if you have the data in a file instead of a string, you can just read the file directly:

df = pd.read_csv("path/to/file", sep='|')

Output:

>>> df
  customer_id first_name  city_name
0      123456        ABC  ARGENTINA
1  2000142707       efgh    LOMELLO

Solution 2:[2]

You can do this:

import pandas as pd
pd.DataFrame([i.split('|') for i in text.replace('"','').split('\r\n')])

You should do some modifications after to have the columns names and delete the last empty row.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 richardec
Solution 2 LCMa