[英]Reading a list of lists from an excel file column and storing it in a python list
我知道這個問題的部分內容可能很簡單,但我是這方面的初學者,並且非常感謝最簡單的解決方案:我有一個 excel(.xlsx 文件),其中一列有其單元格,每個單元格都有一個列表列表數字(數字以空格分隔,每個列表的末尾甚至還有一個空格)。 因此,該列看起來像這樣:
ColumnHeader
[[[9 9 9 9 9 13 ][11 11 11 11 11 11 ][11 11 11 11 11 11 ][9 9 9 9 9 9 ]
[[[9 9 9 9 9 9 ][9 9 9 9 9 9 ]]]
[[[9 9 9 9 ][14 14 14 14 ][13 13 13 13 ]]]
請注意每個列表如何具有不同數量的列表。 另請注意,每個列表列表在其前后分別有一個額外的 [ 和 ]。
我想要做的是理想地在 python 中讀取整個 xlsx 文件(請記住,文件中還有其他只有數字的列),將其存儲在 Pandas 數據框中,但將上面的這一列存儲為列表。 因此,如果我稍后打印此列,我會得到如下內容(如果轉換為列表,該系列將是列表列表:
ColumnHeader
[[9,9,9,9,9,13],[11,11,11,11,11,11],[11,11,11,11,11,11],[9,9,9,9,9,9]]
[[9,9,9,9,9,9],[9,9,9,9,9,9]]
[[9,9,9,9],[14,14,14,14],[13,13,13,13]]
如果我直接將 xlsx 文件讀入 Pandas 數據幀,它顯然將此列讀取為文本,這不是我想要的。
對此的任何幫助將不勝感激。
阿里
我建議您將 incriminated 列作為字符串加載,然后使用此功能將其轉換為嵌套列表。 定義一個接受字符串並返回列表的函數:
import pandas as pd
import ast
# Load some test data
df = pd.DataFrame({'fake_list' : ['[[[9 9 9 9 9 13 ][11 11 11 11 11 11 ][11 11 11 11 11 11 ][9 9 9 9 9 9 ]]]',
'[[[9 9 9 9 9 9 ][9 9 9 9 9 9 ]]] ',
'[[[9 9 9 9 ][14 14 14 14 ][13 13 13 13 ]]]'],
'a': [1,2,3],
'b': [4,5,6]})
def fix_list(s):
s1 = s.strip() #strip white space at the edge of the string
s1 = s1[1:-1] # remove edge parenthesis
s1 = s1.replace(' ',',').replace('][', '],[') # make some replacements so that it looks like a nested list
return ast.literal_eval(s1) # transform string to a nested list
然后將該函數應用於您需要轉換的列:
df['true_list'] = df['fake_list'].apply(fix_list)
print df.true_list[0]
# [[9, 9, 9, 9, 9, 13], [11, 11, 11, 11, 11, 11], [11, 11, 11, 11, 11, 11], [9, 9, 9, 9, 9, 9]]
或者,您可以在使用converters
從 excel 讀取時轉換有罪的列:
df = pd.read_excel('file.xlsx', converters = {'fake_list':fix_list()}
您可以在沒有熊貓的情況下完成,只需使用內置的 csv 庫
from csv import reader
# read csv file as a list of lists
with open('students.csv', 'r') as read_obj:
# pass the file object to reader() to get the reader object
csv_reader = reader(read_obj)
# Pass reader object to list() to get a list of lists
list_of_rows = list(csv_reader)
print(list_of_rows)
如果您想排除第一行,請使用 .pop 函數
list_of_rows.pop(0)
基於: https : //thispointer.com/python-read-csv-into-a-list-of-lists-or-tuples-or-dictionaries-import-csv-to-list/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.