使用pd.read_csv或pd.read_excel,我可以轻松地从csv或Excel文件的指定列中创建数据框。
但是在某些情况下,我只能使用excel文件,而pd.read_excel的运行速度太慢,听说我们可以使用Xlwings来加快速度。
我已经尝试搜索了很多次,但是我找不到如何从Excel中指定列的名称创建Pandas Dataframe的过程(我的文件有数百列,而我只需要使用其中的一些)。非常感谢您的帮助。
pandas:
您可以使用以下代码读取指定的列名称和值:
pd.read_excel('path\\filename.xlsx', sheet_name='products', usecols="B:E")
要了解有关'usecols'的更多信息,请参考documentation。
Xlwings:
要通过pip或conda安装xlwings,请参阅此documentation。
您可以使用以下代码读取指定的列名称和值:
import xlwings as xw
wb = xw.Book(r'path\\filename.xlsx')
sht = wb.sheets['products'] #add your sheetname of your excel file.
sht.range('B1:E1').value #read specified columns names
output: [' date ', 'item_id', 'revenue', 'revenue1', 'revenue2']
sht.range('B1:E1').expand().value #read specified columns names & values.
output: [['item_id', 'revenue', 'revenue1', 'revenue2'], [59.0, 22131846.0, 1212.0, 3223.0], [60.0, 22131847.0, 1213.0, 3224.0]]
我希望这会有所帮助。