【发布时间】:2019-09-09 07:15:03
【问题描述】:
我有一个 Excel 文件,其中包含列中文件夹的文件路径。可能有多个文件路径存储在一行中。 我可以像这样将excel文件读入pandas。
现在我要做的是逐行遍历我的 pandas DataFrame df 并提取存储的目录,以便我可以将它们用作其他功能的输入目录。
如果我使用 iloc 访问数据框中的行,我会得到一个类似 str 的对象,而我想要的每一行都是 list 类型的,所以我可以遍历它。
我的数据框中的变量格式示例。
import pandas as pd
path_1 = '[\'C:\\\\tmp_patients\\\\Pat_MAV_BE_B01_\']'
path_2 = '[\'C:\\\\tmp_patients\\\\Pat_MAV_B16\', \'C:\\\\tmp_patients\\\\Pat_MAV_BE_B16_2017-06-30_08-49-28\']'
d = {'col1': [path_1, path_2]}
df = pd.DataFrame(data=d)
#or read directly excel
# df= pd.read_excel(filepath_to_excel)
for idx in range(len(df)):
paths = df['col1'].iloc[idx]
for a_single_path in paths:
print(a_single_path)
# todo: process all the files found at the location "a single path" with os.walk
【问题讨论】:
-
为什么每个C:\左边都有一个“\”?您是从
csv或xlsx文件中读取的吗?其中每一个都将在字符串中读取,df.explode()将无法处理字符串。 -
@Trenton_M 当我使用 df['col1'].iloc[idx]` 访问
df的行时,左侧会添加一个“\”。我不明白为什么,因为原来的df不存在。 -
@Trenton_M 更新了数据的屏幕截图。在
df的第 14 行,您会注意到我有 2 个单独的文件路径。 -
@Trenton_M
.xlsx -
@Trenton_M 解决了!非常感谢。