我有一个包含10,000张图片的目录。它们标记为1.png,2.png等。我有一个包含青蛙,卡车等10,000个标签的CSV文件。如何循环浏览所有文件以从CSV添加标签? 1.png成为'frog.1.png',假设青蛙是csv中的标签1。
这是我到目前为止所尝试的内容:
import os, sys, fileinput
import pandas as pd
#read csv labels
labels = pd.read_csv('trainLabels.csv',sep=',',header=0,usecols=[1])
#sort files in directory numerically
fnames = sorted([fname for fname in os.listdir(data_dir)
if fname.endswith('.png')], key=lambda f: int(f.rsplit(os.path.extsep, 1)
[0].rsplit(None,1)[-1]))
#Now that order of labels and files match, rename all files using common counter, i
i = 0
for fname in os.listdir(data_dir):
os.rename(fnames[i],labels[i]+'.'+fnames[i])
i = i+1
os.rename不适用于系列,我无法找到适合不同数据类型的约定。
答案 0 :(得分:1)
从外观来看,您的标签变量不可订阅,这意味着您无法按照自己的方式调用其中一个元素。
来自pandas docs:
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html
pd.read_csv返回一个DataFrame或TextParser,而不是我认为你期待的行列表
你不需要"需要"大熊猫读csv:
labels = open('trainLabels.csv','r').read().split('\n')
[labels[i]=labels[i].split(',')[0] for i in range(len(labels))]
#increment 0 above to whatever the column index you want is, this will return the first column
print(labels) #just to check it looks the way you want it to
确定它是一条额外的行,而不是可读的,但是你得到了你想要的数据结构
答案 1 :(得分:1)
为演示做了一些准备工作:
$ for f in `echo "1 2 3 4 10"`; do touch "${f}.png"; done
$ echo "a,b,c,d,e" > names.csv
$ ls
1.png 2.png 3.png 4.png 10.png names.csv
我有1,2,3,4,10
(而不是5
)来演示排序而不是创建10个文件。它与任意数量的文件完全相同。
在Python中,在同一个目录中运行:
>>> import os
>>> import csv
>>> with open('names.csv', 'r') as file:
... reader = csv.reader(file)
... labels = reader.next() # reader is a regular iterator, you can also iterate row by row.
>>> labels
['a', 'b', 'c', 'd', 'e']
>>> fnames = [fname for fname in os.listdir('.') if fname.endswith('.png')]
['1.png', '10.png', '2.png', '3.png', '4.png'] # Because string '10.png' comes earlier than '2.png'
>>> fnames = sorted(fnames, key = lambda f: int(os.path.splitext(f)[0])) # If fnames contain full paths you will need to modify this
>>> fnames
['1.png', '2.png', '3.png', '4.png', '10.png'] # Now we have correct numerical order
>>> len(labels) == len(fnames) # For consistency should check this. Depends on your requirements.
True
>>> for label, fname in zip(labels, fnames):
... os.rename(fname, label + '_' + fname)
结果:
$ ls
a_1.png b_2.png c_3.png d_4.png e_10.png names.csv
注意:
labels
变量包含您想要的名称,而不是某些对象或迭代器。我使用了来自Python standard library的csv阅读器。<number>.png
),你会让你的生活变得更加艰难,并且需要更多代码进行排序。如果你想简化它,只需用前导零填充所有数字,例如对于10000
个文件,文件名为00001.png
,00002.png
,依此类推。操作系统应该自动为您排序。