數據集處理的一些重要技巧:
python merge、concat合并數據集
個人感覺pd處理csv更便捷,而若用rdd讀取數據,則txt更為方便
普通:
1.panda讀取txt
pd.read_table('./1.txt',sep='\t',header=None) #讀入txt文件,分隔符為\t,默認文件沒有表頭,如果有表頭,header=None不寫
2.panda讀取csv
#讀取單個csv
pd.read_csv(category_name_file,header=0,encoding='utf-8')
#讀取目錄下多個并合并
path = files_path
files = os.listdir(path)
train_csv = list(filter(lambda x:(x[0:6] == 'train_' and x[-4:] == '.csv'),files))
data_list=[]
for file_item in train_csv:
tmp = pd.read_csv(path + file_item,header=0)
data_list.append(tmp)
dataset = pd.concat(data_list,ignore_index = False)
3.rdd讀取txt
sc.textFile(filename) #此處可以批量讀入文件,注意用正則表達式正確過濾文件名
4.rdd讀取csv
暫時沒試
5.python直接寫入
with open(csv_file_name,'w',newline = "",encoding='utf-8-sig') as csv_obj:
writer = csv.writer(csv_obj)
header = ["id", "name"] #不限制寫入列數,','作為分隔符號
writer.writerow(header)
for row in keywordslist:
writer.writerow(row) #各列數據也可以使用'\t'作分隔符號
#for key in keywordsMap:
#writer.writerow(key,keywordsMap[key])
csv_obj.close() #直接open的話,一定要寫close。with open可以不一定寫close函數
#同時寫兩個文件
with open(train_file, 'w', encoding='utf-8') as trainf,\
open(test_file, 'w', encoding='utf-8') as testf:
for tds in train_data_set:
trainf.write(tds)
for tts in test_data_set:
testf.write(tts)
注意寫入時,第二個參數所代表的含義!!

文件讀寫模式的參數
1).f.readable() 判斷文件是否可讀,返回True或False
2).f.readline() 每次讀取一行,當讀取到文件末尾時再執(zhí)行readline讀取內容為空
3).f.readlines() 將文件所有內容讀出放到一個列表,每行內容為一個元素
4).f.writable() 判斷文件是否可寫,返回True或False
5).f.closed 判斷文件是否關閉,返回True或False
6).f.write() 將內容寫入文件
7).f.writelines() 將列表內容寫入文件,f.writelines(['hello\n', 'hi\n', 'nice\n'])
8).f.encoding 文件打開時候的編碼,感覺亂碼時可以用一下
9).f.flush() 將內容中的內容刷到硬盤
6).rdd數據寫入txt文件
try:
sc.parallelize(rdd_list_data.collect()).repartition(1).map(
lambda x: str(x[0]) + "\t" + str(x[4])).saveAsTextFile(Config.OutGuessAccessList)
except Exception as e:
print(e)
7).rdd數據寫入csv
暫時沒試