首页 > 解决方案 > 如何从 .CSV 文件中查找前 10 行 AWND 并使用 Python 将结果存储在新的 .CSV 文件中?

问题描述

从 2 年的数据中,找出 AWND 的前 10 个读数/行。将结果存储在 .csv 文件中,并将其命名为 top10AWND.csv。新文件将包含来自 filtersData.csv 的所有列,但只有前 10 个 AWND。

filtersData.csv 的一小部分:

filtersData.csv 的一小部分

我正在使用 Python 3.8 和 Pandas。

我需要从我的过滤数据.csv 文件中找到前 10 个 AWND 读数。然后,我需要将结果存储在一个新文件中。新文件需要包含前 10 个读数的列、STATION、NAME、DATA、Month、AWND 和 SNOW。

我不知道该怎么做。这是我到目前为止所拥有的,但它不起作用。它给了我错误。我遇到的一个错误是 TyperError: list indices must be integers or slices, not list for the filtered_weather = line in code。

import numpy as np  
import pandas as pd
import re 

for filename in ['filteredData.csv']:
    file = pd.read_csv(filename)
    all_loc =dict(file['AWND'].value_counts()).keys()
    most_loc = list(all_loc)[:10]

filtered_weather = ['filteredData.csv'][['STATION','NAME','DATE','Month','AWND','SNOW']] #Select the column names that you want
filtered_weather.to_csv('top10AWND.csv',index=False)

标签: pythonpandascsv

解决方案


你可以这样做:

#This not neccessary unless you want to read several files
for filename in ['filteredData.csv']:
    file = pd.read_csv(filename)
    file = file.sort_values('AWND', ascending = False).head(10)

# If it's only one file you can do
#
#file = pd.read_csv(filename)
#file = file.sort_values('AWND', ascending = False).head(10)

#Considering you want to keep all the columns you can just write the dataframe to the file
file.to_csv('top10AWND.csv',index=False)

推荐阅读