简体   繁体   中英

Why my python only read only 1 column from a CSV file?

Recently, I tried to analyze some csv files, but when I tried to read the csv file into a dataframe, I found that the dataframe had only one column, and the csv file obviously had several columns. The csv file is a test record from a test machine,if I open it with notebook,it looks like this:

在此处输入图像描述


If I open it in excel, it looks like this(over 300 rows):在此处输入图像描述


What I want to do is to take a specific part of the whole csv file(from row 323 to row 327) for analysis , this part looks like this:

在此处输入图像描述

I've tried:

df = pd.read_csv(filepath, sep=';', header=None,)  #read csv with pandas
df.dropna(axis=0, how='all', inplace=True)  #delet empty rows
df = df.iloc[215:300]   #take the data I need from dataframe

But when I ran df.info(), I got this error:

<class 'pandas.core.frame.DataFrame'>
Int64Index: 85 entries, 215 to 299
Data columns (total 1 columns):
0    85 non-null object
dtypes: object(1)
memory usage: 1.3+ KB

There was only 1 column, and what I need was a tabular form with separated columns(like it shows in Excel) so that I could calculate those numbers. I googled this problem and stuggled a few days,no matter what I did, I could only get 1 column. Really need some help or guidance here,thanks in advance.

It is a data-cleaning process, you can read the file in one column, then extract the target rows, then split and expand it.

# same code, just change sep='\n'
df = pd.read_csv(filepath, sep='\n', header=None,)  #read csv with pandas
df.dropna(axis=0, how='all', inplace=True)  #delet empty rows
df = df.iloc[215:300]   #take the data I need from dataframe

# split and expand(new)
dfn = df[0].str.split(',', expand=True)
# then save it as a new file
dfn.to_csv('new_file.csv', index=False, header=None)
# read it again
df = pd.read_csv('new_file.csv')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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