[英]How do I read only a specific column and a specific row from a .csv file in Python?
[英]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. csv文件是一個測試機的測試記錄,如果我用筆記本打開,是這樣的:
如果我用 excel 打開它,它看起來像這樣(超過 300 行):
我要做的是對整個 csv 文件(從第 323 行到第 327 行)的特定部分進行分析,這部分如下所示:
我試過了:
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
但是當我運行 df.info() 時,我得到了這個錯誤:
<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
只有一列,我需要的是一個帶有分隔列的表格形式(就像它在 Excel 中顯示的那樣),以便我可以計算這些數字。 我google了這個問題,糾結了幾天,不管怎么做,都只能得到1列。 在這里真的需要一些幫助或指導,在此先感謝。
這是一個數據清理過程,您可以在一列中讀取文件,然后提取目標行,然后拆分和展開它。
# 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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.