我的 csv 檔案示例:
'Date','Category','Ability'
'21,2,5','Sparrow','Air,land'
'4,5,6','Eagle','Air,Land'
我當前的代碼:
with open(Filepath,'r') as f :
user_read=csv.reader(f)
dict_date=[line['Date'] for line in user_read]
print(dict_date)
錯誤 :
TypeError : list indices must be integer or slices,not str
我的預期輸出:
[21,2,5,4,5,6]
任何想法.. 所以我的類別和能力有單獨的字典
uj5u.com熱心網友回復:
您正在以 dicts 的形式訪問行,可通過 獲取csv.DictReader,而且您沒有quotechar為您正在使用的方言設定 ,因此默認為".
以下內容可以同時按照您想要的方式作業。
import csv
from io import StringIO
# I’m using StringIO to avoid writing a file,
# if the data is in a file keep using with open(…) as f
buf = StringIO(
"""\
'Date','Category','Ability'
'21,2,5','Sparrow','Air,land'
'4,5,6','Eagle','Air,Land'
"""
)
with buf as f:
reader = csv.DictReader(f, quotechar="'")
date = []
date = [
int(v) for row in reader for v in row["Date"].split(",")
]
print(date) # [21, 2, 5, 4, 5, 6]
uj5u.com熱心網友回復:
嘗試:
import csv
all_data = []
with open("data.csv", "r") as f_in:
reader = csv.reader(f_in, quotechar="'")
next(reader) # skip header
for row in reader:
all_data.extend(map(int, row[0].split(",")))
print(all_data)
印刷:
[21, 2, 5, 4, 5, 6]
uj5u.com熱心網友回復:
你可以使用 Pandas 來配合它:
import pandas as pd
df = pd.csv_reader("input.csv")
output = df['Date'].to_list()
輸出將是:
['21,2,5', '4,5,6']
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/490557.html
