csv PythonPandas Dataframe ,列名称显示为字符串,不能涉及

vkc1a9a2  于 2022-12-06  发布在  Python
关注(0)|答案(2)|浏览(131)

i m使用以下格式的csv文件:

"LatD", "LatM", "LatS", "NS", "LonD", "LonM", "LonS", "EW", "City", "State"
   41,    5,   59, "N",     80,   39,    0, "W", "Youngstown", OH
   42,   52,   48, "N",     97,   23,   23, "W", "Yankton", SD
   46,   35,   59, "N",    120,   30,   36, "W", "Yakima", WA
   42,   16,   12, "N",     71,   48,    0, "W", "Worcester", MA
   43,   37,   48, "N",     89,   46,   11, "W", "Wisconsin Dells", WI

当它与:

cities = pd.read_csv("cities.csv")

并尝试使用以下命令调用列:

print(cities[cities.City.str.contains("Y")])

我得到这个错误:

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

我尝试使用修复它,但问题仍然存在:

cities.columns = cities.columns.str.strip()

这是否与第一行的引号有关?如果是,是否有方法通过编程转换它们?
先谢谢你了。

mrwjdhj3

mrwjdhj31#

你可以试着用空字符串替换"(只要列中不包含其他"作为数据,它就可以工作):

from io import StringIO

with open("cities.csv", "r") as f_in:
    df = pd.read_csv(
        StringIO(f_in.read().replace('"', "")), sep=r"\s*,\s*", engine="python"
    )

print(df[df.City.str.contains("Y")])

印刷品:

LatD  LatM  LatS NS  LonD  LonM  LonS EW        City State
0    41     5    59  N    80    39     0  W  Youngstown    OH
1    42    52    48  N    97    23    23  W     Yankton    SD
2    46    35    59  N   120    30    36  W      Yakima    WA
w8biq8rn

w8biq8rn2#

试试这个:

cities["City"].str.contains('Y').any()

参考以了解更多信息:https://www.statology.org/pandas-check-if-column-contains-string/

相关问题