我有一个很大的csv文件,其中包含如下数据:
2018-09, 100, A, 2018-10, 50, M, 2018-11, 69, H,....诸若此类。(没有单独行的连续流)
我想把它转换成dataframe,这样看起来就像
Col1 Col2 Col3
2018-09 100 A
2018-10 50 M
2018-11 69 H这是实际数据的简化版本。请建议什么是最好的方法来接近它。
编辑:澄清一下,我的csv文件没有针对每一行的单独行。所有的数据都在一排。
发布于 2018-11-09 17:20:03
一种解决方案是通过csv模块和this algorithm将单个行分割成块,然后提供给pd.DataFrame构造函数。注意,您的数据格式将是dtype object,因此之后您必须显式地转换数字系列类型。
from io import StringIO
import pandas as pd
import csv
x = StringIO("""2018-09, 100, A, 2018-10, 50, M, 2018-11, 69, H""")
# define chunking algorithm
def chunks(L, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(L), n):
yield L[i:i + n]
# replace x with open('file.csv', 'r')
with x as fin:
reader = csv.reader(fin, skipinitialspace=True)
data = list(chunks(next(iter(reader)), 3))
# read dataframe
df = pd.DataFrame(data)
print(df)
0 1 2
0 2018-09 100 A
1 2018-10 50 M
2 2018-11 69 H发布于 2018-11-09 17:29:48
data = pd.read_csv('tmp.txt', sep=',\s *', header=None).values
pd.DataFrame(data.reshape(-1, 3), columns=['Col1', 'Col2', 'Col3'])返回
Col1 Col2 Col3
0 2018-09 100 A
1 2018-10 50 M
2 2018-11 69 Hhttps://stackoverflow.com/questions/53227868
复制相似问题