我想将一个包含10行的列作为列表导入到Python中。
例如,我在excel中有:1,2,3,4,...,10写在第1-10行的A列中的所有内容。
现在我想将这些单元格导入到Python中,这样我的结果就是:
list = ['One', 'Two', 'Three', 'Four', ..., 'Ten']因为我在编程方面完全是新手,所以我不知道怎么做。所以请告诉我最简单的方法。我找到的所有教程都没有得到我想要的结果。谢谢
我使用的是Python 2.7
发布于 2018-09-14 00:33:15
我不确定你的数据是xlsx格式还是CSV格式。如果是XLSX,则使用this Python Excel tutorial。如果是CSV,就容易多了,您可以按照下面的代码片段进行操作。如果不想使用pandas,可以使用numpy库。使用下面的示例代码片段获取CSV文件的顶行:
import numpy as np
csv_file = np.genfromtxt('filepath/relative/to/your/script.csv',
delimiter=',', dtype=str)
top_row = csv_file[:].tolist()这将适用于只有一列文本的文件。如果您有更多的列,请使用以下代码片段仅获取第一列。'0‘表示第一列。
top_row = csv_file[:,0].tolist()发布于 2018-09-15 06:46:12
发布于 2018-09-14 00:36:56
我推荐安装pandas。
pip install pandas和
import pandas
df = pandas.read_excel('path/to/data.xlsx') # The options of that method are quite neat; Stores to a pandas.DataFrame object
print df.head() # show a preview of the loaded data
idx_of_column = 5-1 # in case the column of interest is the 5th in Excel
print list(df.iloc[:,idx_of_column]) # access via index
print list(df.loc[['my_row_1','my_row_2'],['my_column_1','my_column_2']]) # access certain elements via row and column names
print list(df['my_column_1']) # straight forward access via column name(查看pandas doc)或
pip install xlrd代码
from xlrd import open_workbook
wb = open_workbook('simple.xls')
for s in wb.sheets():
print 'Sheet:',s.name
for row in range(s.nrows):
values = []
for col in range(s.ncols):
values.append(s.cell(row,col).value)
print ','.join(values)(来自https://github.com/python-excel/tutorial/raw/master/python-excel.pdf的示例)
https://stackoverflow.com/questions/52317636
复制相似问题