4 回答

TA貢獻(xiàn)1911條經(jīng)驗(yàn) 獲得超7個(gè)贊
問(wèn)題是 CSV 格式不正確,列表周圍用雙引號(hào)引起來(lái)
list
是 python 數(shù)據(jù)類型,所以它不應(yīng)該用作變量名。lists
通過(guò)將列用雙引號(hào)?引起來(lái)修復(fù) CSV 文件
使用此解決方案
pandas
ast.literal_eval
將字符串評(píng)估回列表
import pandas as pd
from ast import literal_eval
# fix the csv file by wrapping the list with quotes
with open('test.csv', 'r+', newline='') as f:
? ? rows = [s.replace(',[', ',"[').replace(']', ']"').strip() for s in f.readlines()]
? ? f.seek(0)
? ? f.truncate()
? ? f.writelines(s + '\n' for s in rows)
# read the csv and evaluate the list column as lists
df = pd.read_csv('test.csv', converters={'lists': literal_eval})
# display(df)
? ?id? ?name? ? ? lists
0? ?1? Beans? [1, 2, 3]
1? ?2? ?Spam? [5, 6, 7]
2? ?5? ?Spam? [7, 8, 9]
3? ?6? Steak? ? ? ? ?[]
print(type(df.loc[0, 'lists']))
[out]:
list
with open
# converts
id,name,lists
1,Beans,[1,2,3]
2,Spam,[5,6,7]
5,Spam,[7,8,9]
6,Steak,[]
# into
id,name,lists
1,Beans,"[1,2,3]"
2,Spam,"[5,6,7]"
5,Spam,"[7,8,9]"
6,Steak,"[]"

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超6個(gè)贊
如果您無(wú)法更改輸入文件,您仍然可以使用以下代碼處理列表列 -
with open('test.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
stringVal = ","
for row in reader:
newList = row['list'] + "," + stringVal.join(row[None])
print(newList)

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超3個(gè)贊
您可以像這樣引用您的 csv 文件:
"id","name","list"
"1","Beans","[1,2,3]"
"2","Spam","[5,6,7]"
"5","Spam","[7,8,9]"
然后您可以使用csv帶有可選參數(shù)的模塊來(lái)讀取它quoting=csv.QUOTE_ALL。在此之后,您可以將這些“字符串列表”轉(zhuǎn)換為常規(guī)列表。例如,如果這些“字符串列表”只是數(shù)字,那么您可以過(guò)濾結(jié)果,然后將其轉(zhuǎn)換為整數(shù)。這是代碼:
import csv
with open('test.csv', 'r') as fh:
data = list(csv.reader(fh, quoting=csv.QUOTE_ALL))
for i in range(1, 4):
data[i][2] = list(filter(lambda c: str.isnumeric(c), data[i][2]))
data[i][2] = list(map(lambda c: int(c), data[i][2]))
print(*data, sep='\n')
結(jié)果:
['id', 'name', 'list']
['1', 'Beans', [1, 2, 3]]
['2', 'Spam', [5, 6, 7]]
['5', 'Spam', [7, 8, 9]]

TA貢獻(xiàn)1841條經(jīng)驗(yàn) 獲得超3個(gè)贊
問(wèn)題與您的 csv 文件有關(guān)。如果那是實(shí)際文件的樣子,那么它將按照您說(shuō)的那樣進(jìn)行。將列表用雙引號(hào)括起來(lái),如下所示:
id,name,list
1,Beans,"[1,2,3]"
2,Spam,"[5,6,7]"
5,Spam,"[7,8,9]"
添加回答
舉報(bào)