python - 如何从 .CSV 文件中查找前 10 行 AWND 并使用 Python 将结果存储在新的 .CSV 文件中?
问题描述
从 2 年的数据中,找出 AWND 的前 10 个读数/行。将结果存储在 .csv 文件中,并将其命名为 top10AWND.csv。新文件将包含来自 filtersData.csv 的所有列,但只有前 10 个 AWND。
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)
解决方案
你可以这样做:
#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)
推荐阅读
- python - 在对其进行一些分析后从原始数据框中提取信息
- python - 如何为pytest中的每次测试运行创建新的日志文件?
- java - 缺少 linkTo 和 methodOn 声明 Spring HATEOAS STS
- bash - 将文件内容复制到自身的命令行或 bash 方法
- php - Google Cloud Vm 实例不允许我使用 gsuite 帐户通过 phpmailer 发送电子邮件
- python-3.x - 新手试图在类外的另一个函数中使用从类派生的变量
- php - ErrorException 试图获取非对象的属性“语言环境”
- javascript - mxGraph - 保留原始形状颜色
- java - 如何测试基于 SpringSecurity 表达式的访问控制。EL表达式找不到bean
- c# - 根据整数倍数过滤整数列表 - C#