Bridget
Bridget

Reputation: 39

How to find the top 10 rows of AWND from a .CSV file and store the result in a new .CSV file using Python?

From the 2 year data, find the top 10 readings/rows of AWND. Store the result in a file .csv file and name it top10AWND.csv. The new file will have all columns from filteredData.csv, but only the top 10 AWND.

Small portion of the filteredData.csv:

Small portion of the filteredData.csv

I am using Python 3.8 and Pandas.

I need to find the top 10 readings of AWND from my filteredData.csv file. Then, I need to store the results in a new file. The new file needs to have the columns, STATION, NAME, DATA, Month, AWND, and SNOW of the top 10 readings.

I am not sure how to go about doing this. This is what I have so far and it does not work. It gives me errors. One error I run into is a TyperError: list indices must be integers or slices, not list for the filtered_weather = line in the 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)

Upvotes: 1

Views: 1722

Answers (1)

Est
Est

Reputation: 420

You can do something like this:

#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)

Upvotes: 1

Related Questions