熊猫系列字符串路径替换

时间:2018-11-16 16:49:00

标签: pandas

我有一个多列的pandas数据框。对应于一列的条目是字符串,表示存储在我的机器上的图片的路径,例如

df["image_files"][df.index[0]]
df["image_files"][df.index[1]]
.
.
.

将打印

'/home/user_name/Desktop/folder_name_1/folder_name_2/image_name_1.jpeg'
'/home/user_name/Desktop/folder_name_1/folder_name_2/image_name_2.jpeg'
.
.
.

我想在s.t系列中的任何地方替换此字符串的一部分。例如

df["image_files"][df.index[0]]
df["image_files"][df.index[1]]
.
.
.

将打印

'./new_folder_name_1/new_folder_name_2/image_name_1.jpeg'
'./new_folder_name_1/new_folder_name_2/image_name_2.jpeg'
.
.
.

基本上,我希望/home/user_name/Desktop/folder_name_1/folder_name_2/到处都被./new_folder_name_1/new_folder_name_2/取代。谢谢!

1 个答案:

答案 0 :(得分:0)

尝试一下,替换“系列”列中的字符串。

df["image_files"] = df["image_files"].str.replace("/home/user_name/Desktop/folder_name_1/folder_name_2/","./new_folder_name_1/new_folder_name_2/")