本篇文章為大家展示了使用Pandas怎么讀寫CSV文件,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
讀csv
使用pandas讀取
import pandas as pd import csv if name == '__main__': # header=0——表示csv文件的第一行默認(rèn)為dataframe數(shù)據(jù)的行名稱, # index_col=0——表示使用第0列作為dataframe的行索引, # squeeze=True——表示如果文件只包含一列,則返回一個序列。 file_dataframe = pd.read_csv('../datasets/data_new_2/csv_file_name.csv', header=0, index_col=0, squeeze=True) # 結(jié)果:
# 當(dāng)參數(shù)index_col=False 時,自動生成行索引0到n
# csv數(shù)據(jù):
data_1 = [] # 讀取行索引一樣的數(shù)據(jù),保存為list try: # 行索引為i的數(shù)據(jù)有多行,列為'pre_star' data_1.extend(file_dataframe .loc[i]['pre_star'].values.astype(float)) except AttributeError: # 行索引為i的數(shù)據(jù)只有單行, data_1.extend([file_dataframe .loc[i]['pre_star']]) # 多行結(jié)果
# 行索引為i的數(shù)據(jù)只有一行時,不能對file_dataframe .loc[i]['pre_star']使用.values,否則會報錯:
寫csv
使用csv寫
stu1 = [lid, k, pre_count_data[k]] # 打開文件,寫模式為追加'a' out = open('../results/write_file.csv', 'a', newline='') # 設(shè)定寫入模式 csv_write = csv.writer(out, dialect='excel') # 寫入具體內(nèi)容 csv_write.writerow(stu1)
上述內(nèi)容就是使用Pandas怎么讀寫CSV文件,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。