我正在使用python 2.7, 我的文件夹中有文件列表,有数千个文件,看起来像这样:
20180828-024308.dat
20180828-024434.dat
20180828-030335.dat
20180828-032114.dat
20180828-040041.dat
..........
它们是年,月,日,时,分和秒
我想将所有这些文件分组为半小时间隔(注意:年,月和日没有变化)
我想要这样的东西:
1: [20180828-024308.dat,20180828-024434.dat]
2: [20180828-030335.dat,20180828-032114.dat]
3: [20180828-040041.dat,....]
.......
我认为列表对我来说很好,或者对数据框来说可能。
谢谢您的帮助!
答案 0 :(得分:3)
来自:-据我了解, 假设您的数据框看起来像:
Boolean x = true;
int y = 1;
int z = 1;
if(y ==1 && x == true){
z++;
x = false;
}
else{
z--;
x = true;
}
输出:
print(df)
files
0 20180828-024308.dat
1 20180828-024434.dat
2 20180828-030335.dat
3 20180828-032114.dat
4 20180828-040041.dat
df['file_time']= pd.to_datetime(df['files'].str.split('.dat').str[0])
df.groupby([pd.Grouper(key='file_time',freq='1800s')])['files'].apply(list).reset_index()
注意:由于在3:30-4范围内没有文件,因此列表为空。
答案 1 :(得分:0)
我认为您也可以通过基本编程来实现。 因此,首先使用os库加载所有文件,然后使用python获取文件列表。 这是我要说的一句话
import os
folderPath = '/somepath'
filesInFolder = os.listdir(folderPath)
mapOfsimmilarFiles = {}
keyForMaps = 0
for fileNames in sorted(filesInFoldeyr):
timePartOfFile = fileNames.split('-')[-1].split('.dat')[0]
hr = timePartOfFile[0:2]
min = timePartOfFile[2:4]
sec = timePartOfFile[4:]
if len(mapOfsimmilarFiles.keys()) == 0:
mapOfsimmilarFiles[hr+'_'+min] = [fileNames]
else:
minsPresentInMaps = mapOfsimmilarFiles.keys()
hrPresent = [int(h.split('_')[0]) for h in mapOfsimmilarFiles]
minPresent = [(h.split('_')[1]) for h in mapOfsimmilarFiles]
for timeUsed in minsPresentInMaps:
hrPresent = timeUsed.split('_')[0]
minPresent = timeUsed.split('_')[1]
if abs(int(hrPresent)-int(hr)) == 1:
if abs(int(minPresent)-int(min)) <=30:
mapOfsimmilarFiles[timeUsed].append(fileNames)
else:
#same hr but not 30mins so add to map as a new entry
mapOfsimmilarFiles[hr+'_'+min] = [fileNames]
break
mapOfsimmilarFiles[hr+'_'+min] = [fileNames]
我希望这会对您有所帮助,并指导您朝正确的方向前进。
答案 2 :(得分:0)
首先将您的数据转换为dict,然后相应地连接这些字符串。
代码:
d = ['20180828-024308.dat', '20180828-024434.dat', '20180828-030335.dat', '20180828-032114.dat', '20180828-040041.dat']
output = {}
for i in d:
key = i.split('-')[0]
key1 = i.split('-')[1]
# print(output)
if key in output:
if key1[0:2] in output[key]:
output[key][key1[0:2]].append(key1[2:])
else:
output[key][key1[0:2]] = [key1[2:]]
else:
output[key] = {}
output[key][key1[0:2]] = [key1[2:]]
print(output)
# print("_".join("{}_{}".format(k, v) for k, v in output.items()))
main_output = []
for i in output.keys():
temp = []
for j in output[i].keys():
# [s + mystring for s in mylist]
temp.append([i + '-' + j + s for s in output[i][j]])
main_output.extend(temp)
print(main_output)
输出:
{'20180828': {'02': ['4308.dat', '4434.dat'], '03': ['0335.dat', '2114.dat'], '04': ['0041.dat']}}
[['20180828-024308.dat', '20180828-024434.dat'], ['20180828-030335.dat', '20180828-032114.dat'], ['20180828-040041.dat']]