python - 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做的事情?
解决方案
我重新编写了 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)
推荐阅读
- python - 如何在 for 循环中进行网络抓取,而不会丢失 DOM?(Python,硒)
- html - 小屏幕的图像宽度未显示为 100%
- ssl - 如何使用 TLS 连接到 GRPC?
- node.js - 码头集装箱停了很长时间
- typescript - 如何正确覆盖打字稿中的方法?
- c - C 检查归档文件是否被 struct ar_hdr (ar.h) 截断
- android - Flutter 在插件开发期间看不到我的原生通道绑定
- python - 尝试使用 pandas 进行多元回归时发现 ValueError
- css - 反应 js 背景图片
- python - 有没有更好的方法来创建一个多索引数据之前的列?