[英]Extracting the file extensions from file names in pandas
我在pandas dataframe中有一個列FileName
,它包含包含表單文件名的字符串。 文件名中可以包含點('。')。 例如, abcdtxt
是一個txt文件。 我只想讓另一個列FileType
列只包含文件擴展名。
示例DataFrame:
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)
沒有給出所需的輸出。
選項1
apply
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
如果你不想分裂從文件名擴展,那么我會建議名單comprehension-
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.