美文网首页Python-pd
python中panda或者rdd进行txt/csv读取/处理/

python中panda或者rdd进行txt/csv读取/处理/

作者: panjinya | 来源:发表于2020-03-03 14:43 被阅读0次

    数据集处理的一些重要技巧:
    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() 每次读取一行,当读取到文件末尾时再执行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
    暂时没试

    相关文章

      网友评论

        本文标题:python中panda或者rdd进行txt/csv读取/处理/

        本文链接:https://www.haomeiwen.com/subject/aficlhtx.html