日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

python?根據(jù)csv表頭、列號讀取數(shù)據(jù)的實現(xiàn)_python

作者:lovelife110 ? 更新時間: 2022-07-08 編程語言

根據(jù)csv表頭、列號讀取數(shù)據(jù)的實現(xiàn)

讀取csv文件

cvs數(shù)據(jù)截圖如下


在這里插入圖片描述

設(shè)置index_col=0,目的是設(shè)置第一列name為index(索引),方便下面示例演示

data = pandas.read_csv(input1, index_col=0)

輸出結(jié)果

? ? ? ? price ?o_price ?date ?quan
name ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
wood ? ?85.00 ? ?49.99 ?2006 ? 797
chair ?102.50 ? ?49.99 ?2006 ? 799
bed ? ? 77.00 ? ?49.99 ?2006 ? 795
lamp ? 162.50 ? ?49.99 ?2006 ? 800
sofa ? 699.99 ? 269.99 ?2002 ?3094
table ?602.00 ? 269.99 ?2002 ?3093

根據(jù)表頭獲取列數(shù)據(jù)

data[['o_price', 'quan']
# 或者
data.loc[:, ['o_price', 'quan']

輸出結(jié)果

? ? ? ?o_price ?quan
name ? ? ? ? ? ? ? ?
wood ? ? 49.99 ? 797
chair ? ?49.99 ? 799
bed ? ? ?49.99 ? 795
lamp ? ? 49.99 ? 800
sofa ? ?269.99 ?3094
table ? 269.99 ?3093

根據(jù)列號讀取列數(shù)據(jù)

data.iloc[:, [3, 4]]

輸出結(jié)果

? ? ? ?date ?quan
name ? ? ? ? ? ??
wood ? 2006 ? 797
chair ?2006 ? 799
bed ? ?2006 ? 795
lamp ? 2006 ? 800
sofa ? 2002 ?3094
table ?2002 ?3093

根據(jù)index名獲取行數(shù)據(jù)

data.loc[['wood', 'sofa'], :]

輸出結(jié)果

? ? ? ?price ?o_price ?date ?quan
name ? ? ? ? ? ? ? ? ? ? ? ? ? ??
wood ? 85.00 ? ?49.99 ?2006 ? 797
sofa ?699.99 ? 269.99 ?2002 ?3094

根據(jù)列號讀取行數(shù)據(jù)

data.iloc[[0, 1], :]

輸出結(jié)果

? ? ? ?price ?o_price ?date ?quan
name ? ? ? ? ? ? ? ? ? ? ? ? ? ??
wood ? ?85.0 ? ?49.99 ?2006 ? 797
chair ?102.5 ? ?49.99 ?2006 ? 799

iloc和loc區(qū)別

loc是根據(jù)dataframe的具體標簽選取列,而iloc是根據(jù)標簽所在的位置,從0開始計數(shù)。

讀取csv文件并輸出特定列

其實,最開始好不容易輸出了指定列,結(jié)果第二天不小心刪了什么東西,然后就一直報錯。

看上去和前一天能正常輸出的沒有什么差別。折騰了一天多總算是找到問題是什么了,是個很簡單的問題。

其實不是錯誤,只是因為選用的讀取方式不同,所以一直報錯。

源代碼如下

import csv
import pandas as pd?
sheet_name = "員工信息表.csv"
?
#數(shù)據(jù)文件有問題數(shù)據(jù)
with open(sheet_name,encoding = "utf-8",errors = "ignore") as f:
? ??
? ? #可通過列名讀取列值,表中有空值
? ? data= csv.DictReader(_.replace("\x00","") for _ in f)
? ? headers = next(data)
? ? print(headers)
? ? for row in data:
? ? ? ? print(row)
? ? ? ? if row['員工狀態(tài)'] == '2':
? ? ? ? ? ? print(row)
?
? ? #不可通過列名讀取列值,通過第幾列來讀取
? ? #data =csv.reader(_.replace("\x00","") for _ in f)
? ? headers = next(data)
? ? print(headers)
? ? for row in data:
? ? ? ? print(row)
? ? ? ? if row[12]=='2':
? ? ? ? ? ? print(row)

讀取csv文件需要采用:

with open(sheet_name,encoding = "utf-8",errors = "ignore") as f:

如果不加errors = "ignore"會報錯:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbb in position 0: invalid start byte

通過csv.reader讀取csv文件,然后使用列名row['員工狀態(tài)']輸出列值會報錯:

“TypeError: list indices must be integers or slices, not str”

根據(jù)這個報錯百度了好久,一直沒有找到解決方法。

雖然現(xiàn)在最終效果達到了,但是并不清楚具體原因。

源數(shù)據(jù)表里面問題好多啊,感覺需要先做數(shù)據(jù)清洗。唉!好難啊!

原文鏈接:https://blog.csdn.net/qq_33873431/article/details/105833727

欄目分類
最近更新