首页 > 解决方案 > Pandas - 更快地按最后一个 \ 拆分并在新列中使用部分字符串

问题描述

我创建了一个 while 循环,它将文件路径与 pandas 数据框的文件/exe 列分开,并将文件路径放入一个新列中。

#Count rows
rows = len(DF1)
#While loop to grab file path - new column
index = 0
while (index < rows):
  DF1['ParentPath'].iloc[index] = DF1['ParentPathExe'].iloc[index].rsplit('\\', 1)[0]
  DF1['ChildPath'].iloc[index] = DF1['ChildPathExe'].iloc[index].rsplit('\\', 1)[0]
  index = index + 1

这可行,但在 650 万行上速度非常慢。文件/exe 列填充有如下项目:

C:\Windows\System32\conhost.exe
C:\Windows\System32\svchost.exe
C:\Windows\System32\raserver\raserver.exe   

有些文件路径有 3 个“\”,有些有 4、5、6 个“\”等。

我使用以下代码剥离 .exe,这非常快。

#Strip out EXE into new column
DF1['ParentExe'] = DF1['ParentPathExe'].str.split('\\').str[-1]
DF1['ChildExe'] = DF1['ChildPathExe'].str.split('\\').str[-1]

有没有办法避免看起来像我为.exe做的事情?

标签: pythonpandas

解决方案


我重新编写了 Child 和 Parent 行以使用 rsplit 拆分为文件路径和 .exe:

#Split ParentPathExe into path and exe columns
Parent = DF1['ParentPathExe'].str.rsplit("\\", n=1, expand=True)
#Rename columns
Parent.columns = ['ParentPath', 'ParentExe']

    ParentPath                                  ParentExe
0   C:\Program Files (x86)\Wireless AutoSwitch  wrlssw.exe
1   C:\Program Files (x86)\Wireless AutoSwitch  WrlsAutoSW.exs
2   C:\Program Files (x86)\Wireless AutoSwitch  WrlsAutoSW.exs
3   C:\Windows\System32 svchost.exe
4   C:\Program Files (x86)\Wireless AutoSwitch  WrlsAutoSW.exs

#Split ChildPathExe into path and exe columns
Child = DF1['ChildPathExe'].str.rsplit("\\", n=1, expand=True)
#Rename columns
Child.columns = ['ChildPath', 'ChildExe']

    ChildPath   ChildExe
0   C:\Windows\System32 conhost.exe
1   C:\Program Files (x86)\Wireless AutoSwitch  wrlssw.exe
2   C:\Program Files (x86)\Wireless AutoSwitch  wrlssw.exe
3   C:\Program Files\Common Files\microsoft shared...   OfficeC2RClient.exe
4   C:\Program Files (x86)\Wireless AutoSwitch  wrlssw.exe
5   C:\Program Files (x86)\Wireless AutoSwitch  wrlssw.exe

然后将两个数据框合并在一起:

DF1 = pd.concat([Parent, Child], axis = 1)

推荐阅读