当包含 1 或 2 个其他命名属性时,在 Python 中显示 csv 文件中的属性

问题描述 投票:0回答:3

我是Python新手,非常感谢您的帮助。我在 Excel 中创建了一个汽车属性文件,并将其保存为 csv 文件,名为 cars.csv,如下所示:

Car make, colour, price, number of seats, automatic, petrol
Ford, black, 40000,5,yes,no
Tesla, white, 90000,4,yes,no

在标题之后,我有 20 行不同的汽车及其属性。

有人可以帮助我用 python 代码返回所有具有 4 个座位的汽车品牌,或者说成本 40000,或者说这两个属性吗?谢谢你。

python csv opencsv
3个回答
0
投票

您可以使用

Pandas

# pip install pandas
import pandas as pd

df = pd.read_csv('cars.csv', skipinitialspace=True)
print(df)

# Output
  Car make colour  price  number of seats automatic petrol
0     Ford  black  40000                5       yes     no
1    Tesla  white  90000                4       yes     no

过滤您的数据框

out = df[(df['number of seats'] == 4) | (df['price'] == 40000)]
print(out)

# Output
  Car make colour  price  number of seats automatic petrol
0     Ford  black  40000                5       yes     no
1    Tesla  white  90000                4       yes     no

您还可以阅读


0
投票

如果你不想使用任何库,你可以使用这种方法

# The return value of this method can be handled like a list, but its called a generator object
# This method loads all cars from the csv file and yield this data
def load_cars():
    with open('Cars.csv', 'r') as f:
        for counter, line in enumerate(f):
            if counter > 0:# I skipped the header row
                line_content = line.split(", ")
                producer, colour, price, number_of_seats, automatic, petrol = line_content
                yield producer, colour, price, number_of_seats, automatic, petrol # This is like one item in the list

# The statement below is called a list comprehension
# the load_cars method returns the list like object and it iterates over each object, which is put in car
# The car is put in the list if the condition after the if keyword is true
# Each car which fulfills the condition is in the new created list
filtered_cars = [car_data for car_data in load_cars() if car_data[3] == "4" and car_data[2]=="40000"]
filtered_car_names = [car_data[0] for car_data in filtered_cars]

0
投票

您应该在这里使用 pandas.loc[] 函数。如果您使用 pandas 加载 csv,则可以使用 loc 函数仅选择符合您条件的行。

import pandas as pd

# if index was dropped when saving the csv
car_atts = pd.read_csv('path to file as string')

# if index was not dropped
car_atts = pd.read_csv('path to file as string', index_col=0)

4_seater_cars = car_atts.loc[car_atts['number of seats'] == 4]

# if col name is type string
fourty_k_cars = car_atts.loc[car_atts['40000'] == True]

# if col name is type int
fourty_k_cars = car_atts.loc[car_atts[40000] == True]

# you can use the & (AND) to find rows that match both conditions
4_seater_fourty_k_cars = car_atts.loc[
    (car_atts['number of seats'] == 4) &
    (car_atts['40000'] == True)
]

# you can use the | (OR) to find rows that match either condition
4_seater_fourty_k_cars = car_atts.loc[
    (car_atts['number of seats'] == 4) |
    (car_atts['40000'] == True)
]

希望这能回答您的问题。

快乐编码!!

© www.soinside.com 2019 - 2024. All rights reserved.