首页 > 解决方案 > 如何根据 csv 文件的列值获取行并将其保存到 csv 中?

问题描述

我正在尝试使用 python 来完成一项任务,并且我是 python 的初学者。我有很大的 csv 文件,我必须根据特定列的值划分不同的 csv 文件。例如颜色列中包含红色值的所有行,将其保存在一个 csv 文件中;如果有蓝色值,将包含它的行保存在不同的 csv 文件中。

正如我所说,它是一个大的 csv 文件,其中我要过滤的列有很多彼此不同的值,因此编写所有值将是乏味的,但如果没有其他方法,将不会是问题。

有人知道如何完成这项任务吗?

例子:

name  age colour grade
John  15  Red     8
Lucy  14  Blue    7
Katty 15  Red     9
Rob   16  Green   6
Mike  14  Blue    10

解决方案:

red_colour.csv
name  age colour grade
John  15  Red     8
Katty 15  Red     9

green_colour.csv
name  age colour grade
Rob   16  Green   6

blue_colour.csv
name  age colour grade
Lucy  14  Blue    7
Mike  14  Blue    10

编辑:我已经使用了代码,但我不知道为什么我在读取文件时出错。我在 RedHat 机器上阅读它。

# python3.6 example_read.py
Traceback (most recent call last):
  File "example_read.py", line 3, in <module>
    df = pandas.read_csv('/home/usrlogr/lista_blanca.csv')
  File "/usr/local/lib/python3.6/site-packages/pandas/io/parsers.py", line 702, in parser_f
    return _read(filepath_or_buffer, kwds)
  File "/usr/local/lib/python3.6/site-packages/pandas/io/parsers.py", line 429, in _read
    parser = TextFileReader(filepath_or_buffer, **kwds)
  File "/usr/local/lib/python3.6/site-packages/pandas/io/parsers.py", line 895, in __init__
    self._make_engine(self.engine)
  File "/usr/local/lib/python3.6/site-packages/pandas/io/parsers.py", line 1122, in _make_engine
    self._engine = CParserWrapper(self.f, **self.options)
  File "/usr/local/lib/python3.6/site-packages/pandas/io/parsers.py", line 1853, in __init__
    self._reader = parsers.TextReader(src, **kwds)
  File "pandas/_libs/parsers.pyx", line 387, in pandas._libs.parsers.TextReader.__cinit__
  File "pandas/_libs/parsers.pyx", line 705, in pandas._libs.parsers.TextReader._setup_parser_source
FileNotFoundError: [Errno 2] File b'/home/usrlogr/lista_blanca.csv' does not exist: b'/home/usrlogr/lista_blanca.csv'

有谁知道是什么问题?我安装了 Python 3.6.8 和 Pandas

标签: pythonpandascsvdataframerow

解决方案


获取数据中所有不同的颜色。然后根据该颜色过滤每一行。最后,保存到 csv 文件中。

import pandas as pd
df = pd.read_csv('myfile.csv')
#get all distinct colour
for color in df['colour'].unique():
    #filter the data for each color and excluding John
    df_temp = df[(df['colour'] == color) & (df['name'] != 'John')] 
    #save into csv file using filename: color_colour.csv
    df_temp.to_csv(color.lower() + '_colour.csv', index=False)

推荐阅读