我正在练习Pandas,并有以下任务:
创建一个列表,其元素是每个.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”?或者有更好的方法来解决这个问题吗?
[df.shape[1] for df in dataframes.values()]
吗? - Peter Gibsondict.values()
方法。 - Vivek Jha