简体   繁体   English

在字典中阅读时“没有要从文件中解析的列”

[英]“No columns to parse from file” when reading in dictionary

I'm trying to take a dictionary object in python, write it out to a csv file, and then read it back in from that csv file.我正在尝试在 python 中获取字典 object,将其写入 csv 文件,然后从该 Z6287CB5675FFE884FZ 文件中读回

But it's not working.但它不起作用。 When I try to read it back in, it gives me the following error:当我尝试重新读取它时,它给了我以下错误:

EmptyDataError: No columns to parse from file

I don't understand this for two reasons.我不明白这有两个原因。 Firstly, if I used pandas very own to_csv method, it should be giving me the correct format for a csv.首先,如果我使用 pandas 非常自己的 to_csv 方法,它应该为我提供 csv 的正确格式。 Secondly, when I print out the header values (by doing this: print(df.columns.values) ) of the dataframe that I'm trying to save, it says I do in fact have headers ("one" and "two".) So if the object I was sending out had column names, I don't know why they wouldn't be found when I'm trying to read it back.其次,当我打印出我试图保存的 dataframe 的 header 值(通过这样做: print(df.columns.values) )时,它说我确实有标题(“一个”和“两个” .) 所以如果我发送的 object 有列名,我不知道为什么当我试图读回来时找不到它们。

import pandas as pd
testing = {"one":1,"two":2 }
df = pd.DataFrame(testing, index=[0])

file = open('testing.csv','w')

df.to_csv(file)

new_df = pd.read_csv("testing.csv")

What am I doing wrong?我究竟做错了什么?

Thanks in advance for the help!在此先感谢您的帮助!

The default pandas.DataFrame.to_csv takes a path and not an text io .默认pandas.DataFrame.to_csv采用路径而不是text io Just remove the file declaration and directly use the path, pass index = False to skip indexes.只需删除文件声明并直接使用路径,通过index = False跳过索引。

import pandas as pd
testing = {"one":1,"two":2 }
df = pd.DataFrame(testing, index=[0])

df.to_csv('testing.csv', index = False)

new_df = pd.read_csv("testing.csv")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM