简体   繁体   English

当列标题包含正斜杠时,如何从 CSV 文件中读取数据?

[英]How to read data from a CSV file when the column heading contains a forward slash?

I want to check whether a column in a CSV file is storing any data that is equal to a given input.我想检查 CSV 文件中的列是否存储了任何等于给定输入的数据。

I have a csv file which I'll call myFile.csv , I'm using pandas to read it as follows:我有一个 csv 文件,我将其命名为myFile.csv ,我使用pandas来读取它,如下所示:

import pandas as pd

...

path = r'C:\Users\...\myFile.csv'
df = pd.read_csv(path)

One of the columns I'm trying to read data from has the heading Country/Region .我试图从中读取数据的列之一具有标题Country/Region What I'm trying to do is check whether Country/Region contains any rows with the value 'someRegion'我要做的是检查Country/Region是否包含任何值为'someRegion'

region = 'someRegion'

for item in df.Country/Region:
    if item == region:
        #doSomething

The issue I'm having is that when I do this I get the following error:我遇到的问题是,当我这样做时,我收到以下错误:

AttributeError: 'DataFrame' object has no attribute 'Country'

Is there any way for this to work without changing the name of the column heading in the CSV file to something without a forward slash as this is not an option?有没有什么办法可以在不将 CSV 文件中的列标题名称更改为没有正斜杠的名称的情况下工作,因为这不是一个选项?

(I'm using the latest version of pandas and python 3.7.7 ) (我使用的是最新版本的pandaspython 3.7.7

you can reference column in following way:您可以通过以下方式引用列:

In [44]: for item in df['country/region']:
    ...:     if item == region:
    ...:         #do something
    ...:

Python won't interpret the following line of code in the way you want it to, hence the error: Python 不会以您希望的方式解释以下代码行,因此出现错误:

for item in df.Country/Region:

The Python Interpreter thinks the '/' symbol is a division operator and not part of the column name. Python 解释器认为“/”符号是除法运算符,而不是列名的一部分。

If the name of the column contains a character that acts as an operator, like "/", you need to address your DataFrame using the [] bracket notation.如果列的名称包含充当运算符的字符,例如“/”,则需要使用 [] 括号表示法来寻址 DataFrame。

if "region" in df["Country/Region"]:
    pass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM