简体   繁体   中英

Create pandas dataframe from string (in csv format)

I have a string in this format:

"A1","B1","C1","D1","E1","F1","G1","H1"\\n"A2","B2","C2","D2","E2","F2" etc

where A to H are columns and the numbers refer to the rows.

I'm looking for the quickest way to create a pandas dataframe.

A long (in time to complete) approach I tried is to use:

df = pd.DataFrame()
for row in data:
    reader = csv.reader(row)
    mylist = []
    for element in reader:
        if element!=['','']:
            mylist.append(element[0])
    df2 = pd.DataFrame([mylist])
    df = df.append(df2)

I'm looking for a quicker way.

I believe you need StringIO with read_csv :

import pandas as pd

data = '"A1","B1","C1","D1","E1","F1","G1","H1"\n"A2","B2","C2","D2","E2","F2"'
df = pd.read_csv(pd.compat.StringIO(data), header=None)

print (df)


    0   1   2   3   4   5    6    7
0  A1  B1  C1  D1  E1  F1   G1   H1
1  A2  B2  C2  D2  E2  F2  NaN  NaN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM