使用熊猫数据框读取一个字符串

时间:2018-01-19 20:52:15

标签: python pandas

我有一个变量字符串,如下所示。我需要将其转换为数据帧并读取为csv文件以进行进一步处理。请告诉我它是如何实现的?

A,B,C,D,E,F
1,1305,21:44,0,34.34,
2,1304,21:43,0,31.43,
3,1303,21:42,0,,

我尝试了以下代码,但出现ValueError: DataFrame constructor not properly called!错误。有人可以帮忙吗?

parsed_data = pd.read_csv(io.StringIO(pd.DataFrame(string, columns=settings.COLUMNS).to_csv(index=False)))

1 个答案:

答案 0 :(得分:3)

这应该有用。

import pandas as pd
import io

zz = """A,B,C,D,E,F
1,1305,21:44,0,34.34,
2,1304,21:43,0,31.43,
3,1303,21:42,0,,
"""

# Assuming the first column is the index,
# the first row of data contains column names
df = pd.read_table(io.StringIO(zz), index_col=0, sep=',')
df.head()

#       B      C  D      E   F
# A                           
# 1  1305  21:44  0  34.34 NaN
# 2  1304  21:43  0  31.43 NaN
# 3  1303  21:42  0    NaN NaN