python - 使用熊猫从excel文件中读取特定列
问题描述
我有一个充满 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 文件:
推荐阅读
- c - 如何在循环中重用 *char[]?
- c++ - OpenMP 运行速度比单线程慢
- mysql - 物料清单数据库SQL的模型数据结构
- python-3.x - 匹配词频并从 pandas 中的另一个数据框中分配最大分数的类别和子类别
- html - 在选择标签泰卢固语中从底部裁剪文本
- flutter - 将数据保存到本地存储时被覆盖的文本 - Flutter
- python - django 模型 select_related 或 prefetch_related 子模型
- pyspark - AWS Glue-如何在 S3 中将动态帧编写为 .txt 文件并使用“|” 作为分隔符
- java - Ldaptive 检索所有用户属性
- c# - 使用 HttpWebRequest 从 C# 上传图像到使用 PUT 方法的 NodeJS Express