尝试在Pandas Dataframe中转换列表,但得到意外的输出

import pandas as pd
reader=pd.read_csv("txt",sep='\t',chunksize=500)
sl=[]
for chunk in reader:
    sl.append(chunk)
    break

pd.DataFrame(sl)# Trying to conver into DF```


Output:
   0
0 norm...




最佳答案

遍历reader返回DataFrame中的chunk。因此,您需要访问每个values chunk中的DataFrame。下图显示了以增量方式加载csv,并将其数据放入列表中,然后将其重新构成为DataFrame的情况。

import pandas as pd
from pandas.compat import StringIO

print(pd.__version__)

csvdata = """ID,week,sale
A,1,1
A,2,4
A,3,10
B,1,7
B,2,2.3
B,3,4.4"""

with open('txt.csv', 'w') as the_file:
    the_file.write(csvdata)

reader=pd.read_csv('txt.csv', chunksize=2)

sl=[]
for chunk in reader:
    # each chunk is a DataFrame
    print("Chunk type {}".format(type(chunk)))
    print("Chunk values {}".format(chunk.values))
    for row in chunk.values:
        sl.append(row)
print(sl)

df = pd.DataFrame(sl)
print(df)

关于python - 尝试在pandas Dataframe中转换列表,但在列表中包含文本时却得到意外的输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55697525/

10-12 21:26