问题描述
我正在尝试使用 read_csv
将逗号分隔的文本文件读入Python.但是,Python正在获取标头并将其向右移一位.
具有比我实际少的列的数据文件示例:(具有更多数据的示例文件:
我还尝试了 df_fires = pd.read_csv(infile_fire).reset_index()
,尽管它确实创建了新索引(如我所愿),但它也会移动 226 列上方,并将其命名为 index
,而不是应将其命名为 DAY
的名称.
我也尝试了以下方法,但是仍然得到了相同的结果(标题移动)
df = pd.read_csv(infile_fire)
df = pd.read_csv(infile_fire,index_col = None)
df = pd.read_csv(infile_fire,index_col = 0)
我该如何解决?我只想读入文本文件,并让Python设置新索引并将标头保持原样.
将索引设置为False可解决此问题.
df = pd.read_csv(infile_fire,index_col = False)
I am trying to read in a comma separated text file into Python with read_csv
. However, Python is taking the header and shifting it over to the right by one.
Data file example with less columns than I actually have: (example file with more data: https://www.dropbox.com/s/5glujwqux6d0msh/test.txt?dl=0)
DAY,TIME,GENVEG,LATI,LONGI,AREA,CHEM
226, 1200, 2, -0.5548999786D+01, 0.3167600060D+02, 0.1000000000D+07, NaN
226, 1115, 2, -0.1823500061D+02, 0.3668500137D+02, 0.1000000000D+07, NaN
If I try the following (where infile_fire
is the above txt file):
df_fires = pd.read_csv(infile_fire,sep="\,",skipinitialspace=True,engine='python')
I get this below. As you can see, DAY
is actually above what should be the TIME
column.(Note that the value in the AREA
column comes from data I have in the larger dataset which isn't shown in the sample subset above)
I also tried df_fires = pd.read_csv(infile_fire).reset_index()
, and though it does create a new index (as I'd like it to do), it also moves the 226
column over and names it index
instead of DAY
as it should.
I've also tried the following, but still got the same result (shifted headers)
df = pd.read_csv(infile_fire)
df = pd.read_csv(infile_fire,index_col=None)
df = pd.read_csv(infile_fire,index_col=0)
How can I fix this? I just want to read in the text file and have Python set up a new index and keep the headers as is.
Setting index to False solves this issue.
df = pd.read_csv(infile_fire,index_col=False)
这篇关于read_csv转换列标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!