从pandas中提取文件名的文件扩展名

5

我有一个名为FileName的pandas数据帧列,其中包含字符串形式的文件名。文件名中可以包含点('.'). 例如,a.b.c.d.txt是一个txt文件。我只想要另外一列FileType,其中包含文件扩展名。

样本数据框:

FileName

a.b.c.d.txt

j.k.l.exe

处理后:

FileName    FileType

a.b.c.d.txt txt

j.k.l.exe   exe

我尝试了以下内容:

X['FileType'] = X.FileName.str.split(pat='.')

这帮助我在 . 上分割字符串。但是如何获取最后一个元素,即文件扩展名?
类似以下内容:
X['FileType'] = X.FileName.str.split(pat='.')[-1]

X['FileType'] = X.FileName.str.split(pat='.').pop(-1)

未获得预期的输出结果。

2个回答

8

选项1
应用

df['FileType'] = df.FileName.apply(lambda x: x.split('.')[-1])

选项2
使用str两次

df['FileType'] = df.FileName.str.split('.').str[-1]

选项2b
使用rsplit(感谢@cᴏʟᴅsᴘᴇᴇᴅ)。

df['FileType'] = df.FileName.str.rsplit('.', 1).str[-1]

所有结果都在:

      FileName FileType
0  a.b.c.d.txt      txt
1    j.k.l.exe      exe

Python 3.6.4, Pandas 0.22.0


4
作为对您解决方案的轻微改进,我建议使用简单的 rsplit——df.FileName.str.rsplit('.', 1).str[-1]...这样只从右侧分割一次,因此应该更有效率。 - cs95

3

如果你不想将扩展名从文件名中分离出来,我建议使用列表推导式——

使用 str.rsplit 的推导式

df['FileType'] = [f.rsplit('.', 1)[-1] for f in df.FileName.tolist()]
df

      FileName FileType
0  a.b.c.d.txt      txt
1    j.k.l.exe      exe

如果您想分离路径和文件名,有几种选择。

os.path.splitext

import os

pd.DataFrame(
    [os.path.splitext(f) for f in df.FileName], 
    columns=['Name', 'Type']
)
 
      Name  Type
0  a.b.c.d  .txt
1    j.k.l  .exe

str.extract

df.FileName.str.extract(r'(?P<FileName>.*)(?P<FileType>\..*)', expand=True)

      Name  Type
0  a.b.c.d  .txt
1    j.k.l  .exe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接