簡體   English   中英

Pythonic方式循環字典

[英]Pythonic way to loop over dictionary

我正在練習熊貓並完成以下任務:

創建一個列表,其元素是每個.csv文件的列數


.csv文件存儲在以年為單位的字典directory

我使用字典理解dataframes (再次按年份鍵入)將.csv文件存儲為pandas數據幀

directory = {2009: 'path_to_file/data_2009.csv', ... , 2018: 'path_to_file/data_2018.csv'}

dataframes = {year: pandas.read_csv(file) for year, file in directory.items()}

# My Approach 1 
columns = [df.shape[1] for year, df in dataframes.items()]

# My Approach 2
columns = [dataframes[year].shape[1] for year in dataframes]

哪種方式更“Pythonic”? 或者有更好的方法來解決這個問題嗎?

您的方法將完成它...但我不喜歡讀取整個文件並創建數據幀只是為了計算列。 你可以通過閱讀每個文件的第一行並計算逗號的數量來做同樣的事情。 請注意,我添加1是因為總有一個逗號少於列。

columns = [open(f).readline().count(',') + 1 for _, f in directory.items()]

你的方法2:

columns = [dataframes[year].shape[1] for year in dataframes]

更加Pythonic和簡潔與未來在合並,繪圖,操縱等數據幀的使用,因為理解中隱含了鍵,並且形狀給出了列數

你可以使用:

columns = [len(dataframe.columns) for dataframe in dataframes.values()]

正如@piRSquared所提到的,如果您的唯一目標是獲取數據幀中的列數,則不應讀取整個csv文件,而應使用read_csv函數的nrows關鍵字參數。

import os
#use this to find files under certain dir, you can filter it if there are other files
target_files = os.listdir('path_to_file/')       
columns = list()
for filename in train_files:
    #in your scenario @piRSquared's answer would be more efficient.
    columns.append(#column_numbers) 

如果您希望文件名中包含年份的列,則可以過濾文件名並更新字典,如下所示:

year = filename.replace(r'[^0-9]', '')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM