加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python-将excel中的某些列读取到数据框

发布时间:2020-12-17 17:35:24 所属栏目:Python 来源:网络整理
导读:我想将某些列从excel文件读入数据帧,但是我想用其列标题名称指定该列. 例如,我有一个excel文件,在工作表2中有两列:A列为“ number”,B列为“ ForeignKey”.我想将“ ForeignKey”导入数据框.我使用以下脚本进行了此操作: xl_file = pd.read_excel('D:/Snap

我想将某些列从excel文件读入数据帧,但是我想用其列标题名称指定该列.

例如,我有一个excel文件,在工作表2中有两列:A列为“ number”,B列为“ ForeignKey”.我想将“ ForeignKey”导入数据框.我使用以下脚本进行了此操作:

xl_file = pd.read_excel('D:/SnapPython/TestDF.xlsx',sheet_name='Sheet 2',usecols=[0,1]) 

它在我的xl_file中显示以下内容:

       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']) 

根据以下链接中的讨论,以上代码适用于read_csv.

[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

  • 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']

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读