我想将某些列从excel文件读入数据帧,但是我想用其列标题名称指定该列.
例如,我有一个excel文件,在工作表2中有两列:A列为“ number”,B列为“ ForeignKey”.我想将“ ForeignKey”导入数据框.我使用以下脚本进行了此操作:
xl_file = pd.read_excel('D:/SnapPython/TestDF.xlsx',sheet_name='Sheet 2',usecols=[0,1])
number ForeignKey
0 1 abc
1 2 def
2 3 ghi
如果列数较少,我可以通过指定usecols = [1]来获取“ ForeignKey”.但是,如果我有很多列并且知道列名模式,则通过指定列名会更容易.我尝试了以下代码,但它给出了空的数据框.
xl_file = pd.read_excel('D:/SnapPython/TestDF.xlsx',usecols=['ForeignKey'])
[How to drop a specific column of csv file while reading it using pandas?
有办法读取Excel文件吗?
先感谢您
最佳答案
有解决方案,但csv的处理方式与excel不同.
从文档,对于csv:
usecols : list-like or callable,default None
For example,a valid list-like usecols parameter would be [0,1,2] or [‘foo’,‘bar’,‘baz’].
对于Excel:
usecols : int or list,default None
@H_301_57@If None then parse all columns, If int then indicates last column to be parsed If list of ints then indicates list of column numbers to be parsed If string then indicates comma separated list of Excel column letters and column ranges (e.g. “A:E” or “A,C,E:F”). Ranges are inclusive of both sides
所以您需要这样称呼它:
xl_file = pd.read_excel('D:/SnapPython/TestDF.xlsx',usecols='ForeignKey')
并且如果您还需要“数字”:
xl_file = pd.read_excel('D:/SnapPython/TestDF.xlsx',usecols='number,ForeignKey')
编辑:
您需要输入excel列的名称而不是数据的名称.
另一个答案解决了这个问题.
但是您不需要’B:B’,’B’可以解决问题,但不会提高数字的使用价值.
如果您可以在短时间内加载所有数据,也许解决此问题的最佳方法是解析所有列,然后选择所需的列:
xl_file = pd.read_excel('D:/SnapPython/TestDF.xlsx',sheet_name='Sheet 2')['ForeignKey']