如何从列表中正确创建pandas DataFrame:所有列都合并在单个列“ 0”中

时间:2019-02-23 14:53:03

标签: python pandas dataframe

我有此代码:

print("body['csvData']", body['csvData'])

print("===============================")

csvData = pd.DataFrame([x.split(';') for x in str(body['csvData']).split('\n')])

print("TYPE csvData", type(csvData))

print(csvData.head())

它从React.js接收POST正文请求的内容,并尝试将csvData转换为pandas DataFrame。

我得到以下输出:

body['csvData']
 NUM,AIRLINE_ARR_ICAO,WAKE,SIBT,SOBT,PLANNED_TURNAROUND,DISTANCE_FROM_ORIGIN,DISTANCE_TO_TARGET
1,AEA,H,2016-01-01 04:05:00,2016-01-01 14:10:00,605,9920.67,5776.89
2,AEA,H,2016-01-01 04:25:00,2016-01-01 06:30:00,125.0,10060.80,483.93
3,AVA,H,2016-01-01 05:05:00,2016-01-01 07:05:00,120.0,8033.86,8033.86
4,IBE,H,2016-01-01 05:20:00,2016-01-01 10:40:00,320.0,6000.00,8507.73
5,IBE,H,2016-01-01 05:25:00,2016-01-01 10:50:00,325.0,6698.42,6698.42

===============================
TYPE csvData <class 'pandas.core.frame.DataFrame'>
                                                0
0  NUM,AIRLINE_ARR_ICAO,WAKE,SIBT,SOBT,PLANNED_TU...
1,AEA,H,2016-01-01 04:05:00,2016-01-01 14:10:0...
2,AEA,H,2016-01-01 04:25:00,2016-01-01 06:30:0... 
3,AVA,H,2016-01-01 05:05:00,2016-01-01 07:05:0... 
4,IBE,H,2016-01-01 05:20:00,2016-01-01 10:40:0...

看起来csvData已转换为pandas DataFrame,但是所有列都合并为一个名为0的列。

print(csvData.dtypes)

输出:

0    object
dtype: object

1 个答案:

答案 0 :(得分:1)

pd.read_csv()需要csv文件的位置。您现在应该添加下面给出的代码。

csvData.columns = csvData.iloc[0]
csvData.reindex(csvData.index.drop(0))