将字符串转换为熊猫数据框

时间:2018-07-27 19:06:14

标签: python pandas

import pandas as pd
from StringIO import StringIO
msg1 = '"     feature1  feature2       UIN  Comop  YYYYMM  Sales  Month          grain\\n0         212       212  F1230901  220ES  201202    212      2  F1230901220ES\\n"'
def result_trans(res_str):
    print res_str 
    res_str = StringIO(res_str)


    part_hist_df = pd.read_csv(res_str, sep="\s+")
    return part_hist_df


print result_trans(msg1)

我需要将此字符串转换为如下所示的pandas数据框。请帮忙。

feature1  feature2       UIN     Comop  YYYYMM  Sales  Month          grain
212       212          F1230901  220ES  201202    212      2  F1230901220ES

1 个答案:

答案 0 :(得分:0)

IIUC,使用pd.read_table

msg1 = '"     feature1  feature2       UIN  Comop  YYYYMM  Sales  Month          grain\n0         212       212  F1230901  220ES  201202    212      2  F1230901220ES\\n"'

pd.read_table(sio(msg1.strip('""').replace('\\n','\n')), delim_whitespace=True)

如果数据只是字符串,则无需strip

pd.read_table(io.StringIO(msg1), delim_whitespace=True)