繁体   English   中英

使用pandas从excel文件中读取特定列

[英]Reading specific column from excel file using pandas

我有一个包含excel文件和子文件夹的文件夹。子文件夹还包含excel文件。

使用os.walk()我已经能够遍历每个子文件夹并从该excel文件中获取数据。我的问题是,我想从所有excel文件中仅获取移动数字列并将它们存储在数据库中。 问题是,每个excel文件中手机号码的列名不同,并且有数千个excel文件。

所以我决定按其数据类型和长度获取列。 (例如,如果列数据类型是整数,并且该特定列中每个单元格的长度为10,那么我将推送该数据。)

但我不明白该怎么做。 我通过列和行循环,但我得到的只是重复数据或错误。 有人可以帮我解决这个问题吗? 如果你帮忙导致我这样做两天但是失败了会很高兴。 提前致谢。

 def file_access(file_path_list):
    for path in file_path_list:
        if path.endswith(('xlsx' , 'xls' , 'XLS')):
            print '------------------------------\n\n'
            folder = path.split('/')[-2]
            sheet = path.split('/')[-1]
            print folder , sheet

            df = pd.read_excel(path, sheet_name=None, header=None)

            # Here i am trying to get data from df object but failing to do so.
            # You can suggest me code from this stage. 

要获取许多excel文件中的电话号码,您可以尝试以下代码:

import pandas as pd
import xlrd
import os

mydir = (os.getcwd()).replace('\\','/') + '/'

#Get all excel files include subdir
filelist=[]
for path, subdirs, files in os.walk(mydir):
    for file in files:
        if (file.endswith('.xlsx') or file.endswith('.xls') or file.endswith('.XLS')):
            filelist.append(os.path.join(path, file))
number_of_files=len(filelist)

# Get data of cells from excel
data=[]
for i in range(number_of_files):
    #df.append(pd.read_excel(r''+ mydir +filelist[i]))
    df=pd.read_excel(r''+filelist[i])
    l=len(df.iloc[0])
    for n in range(l):
        if len(str(df.iloc[0][n])) >= 10:
            data.append(df.iloc[:][df.axes[1][n]])
            break
res=[]
for i in range(len(data)):
    res.append(data[i].values.tolist())
print(res)

要从不同列的名称获取所有电话数据,它会使用电话号码的长度来区分其他列数据。 对于这种情况,我使用了我国使用的电话号码长度为11(例如:82330403045)。

输出:

>>> data
[0    82330403045
1    82330403046
2    82330403047
3    82330403048
Name: Phone, dtype: int64, 0    82330403049
1    82330403050
2    82330403051
3    82330403052
Name: PhoneCell, dtype: int64]

>>> res
[[82330403045, 82330403046, 82330403047, 82330403048], [82330403049, 82330403050, 82330403051, 82330403052], [82330403049, 82330403050, 82330403051, 82330403052], [82330403045, 82330403046, 82330403047, 82330403048], [82330403049, 82330403050, 82330403051, 82330403052], [82330403049, 82330403050, 82330403051, 82330403052]]

您可以将此输出数据用于数据库。

我的Excel文件:

Book1.xlsx文件:

Book2.xlsx文件:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM