【问题标题】:How can I combine files with matching ending characters?如何组合具有匹配结尾字符的文件?
【发布时间】:2019-10-03 02:05:41
【问题描述】:

我有名为“name1 01.01.2018.xlsx”、“name1 01.01.2018.xlsx”、“name2 12.23.2019.xlsx”等的 excel 文件。我想加入所有日期匹配的文件(最后 10 个字符)。

我可以通过以下方式加入他们所有人:

import glob
import os
import pandas

os.chdir('filepath')
files = [pd.read_excel(p, skipfooter=1) for p in glob.glob("*.xlsx")]
df = files[0].drop(files[0].tail(0).index).append([files[i].drop(files[i].tail(0).index) for i in range(1,len(files))])

如何仅在最后一个字符匹配时加入?我没有最后 10 个字符的选项列表,我希望它自动更新。

【问题讨论】:

  • join 是什么意思?您想将它们叠加在一起吗?还是紧挨着?

标签: python pandas operating-system glob


【解决方案1】:

嗯,首先,我们需要重新格式化您的代码。虽然加入数据框的行是正确的,但它很难阅读并且可以更有效地完成:

import glob
import os
import pandas as pd

os.chdir('filepath')
files = [pd.read_excel(p, skipfooter=1) for p in glob.glob("*.xlsx")]

# drop the tail of all files
files = [f.drop(f.tail(0).index) for f in files]

# join all files
df = files[0].append(files[1:])

然后,我们需要对其进行一些更新,以便您可以检查您加载的文件的文件名,并通过某种方式将它们绑定回您创建的 Dataframe。

import glob
import os
import pandas as pd

os.chdir('filepath')

# store last 10 characters of original filename
files = [(p[-10:], pd.read_excel(p, skipfooter=1)) for p in glob.glob("*.xlsx")]

# drop the tail of all files
files = [(p, f.drop(f.tail(0).index)) for p, f in files]

# group files by last 10 characters of filename
files = {p: [g for n, g in files if n == p] for p in set(p for p, f in files)}

# join all files with same last 10 characters
for key, value in files.items():
    files[key] = value[0].append(value[1:])

【讨论】:

  • 感谢您的回答和帮助清理代码。我在一个文件夹中尝试了两个文件,“name1 06.02.2019.xlsx”和“name2 06.02.2019.xlsx”,files.keys() 返回了 dict_keys(['.2019.xlsx'])
  • 是点的原因吗?
  • 没关系,只需将 10 更改为 15 即可解决问题(“.xlsx”也算在内)。谢谢!
  • @LuanVieira 查看第 8 行:这决定了密钥。看起来您实际上需要文件名的最后 15 个字符,而不是您说的最后 10 个字符 - 请记住,扩展名是文件名的一部分!
  • 实际上,它仅在所有文件以相同的最后 15 个字符结尾时才有效。否则我会得到 IndexError Traceback (last recent call last) in 16 # join all files with the same last 10 characters 17 for key, value in files.items(): ---> 18 个文件[key] = value[0].append(value[1:])
猜你喜欢
  • 2011-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-03
  • 2023-01-24
  • 2013-03-09
相关资源
最近更新 更多