PandasCSV中的匹配变量值

uajslkp6  于 2022-09-21  发布在  其他
关注(0)|答案(3)|浏览(211)

我有一个CSV文件,其中包含城镇、县和国家的列表。

Town           County  Country      
            Ampthill     Bedfordshire  England      
             Arlesey     Bedfordshire  England

我想要能够检查一个城镇是否在名单中,如果一个城镇在名单中,那么我想知道这个国家是什么。目前使用的是Pandas。

关于如何检查Pandas体内是否存在变量值的任何想法。

mbjcgjjk

mbjcgjjk1#

试试这个:

import pandas as pd
df = pd.read_csv('YOUR_PATH_HERE')

# to check if a single town

country = df.loc[(df['Town'] == 'Arlesey')]['Country']

# using the isin() operator

df.loc[df['Town'].isin(['Arlesey'])]['Country']

输出:

使用isin()是一个非常强大的工具,可以满足您的需求。它接受一个列表,如果值在列表中,则返回True。如果您想要整个 Dataframe ,只需删除末尾的['Country]

Town      County       Country
1   Arlesey Bedfordshire    England

如果需要实际值,可以使用pd.series.values


# using values[0] because it is the first element in the array

df.loc[df['Town'].isin(['Arlesey'])]['Country'].values[0]
izkcnapc

izkcnapc2#

如果您只需要相应交叉点处的值:

import pandas as pd

df = pd.read_csv('test.csv')

if 'ampthill' in df['town'].values:
    index = df.town[df.town == 'ampthill'].index.tolist()[0]
    country = df.loc[index, 'country']

print(country)
>>> england
dxxyhpgq

dxxyhpgq3#

所以这对我来说很管用。

from pathlib import Path
import pandas as pd
home = str(Path.home())
csv_folder = Path(r"TO_CSV_FOLDER")

csv =  csv_folder / 'town-county-country.csv'
town = 'Ampthill'
with open(csv,'r') as csv:
    ctu = ["Town","County","Country"]
    cas = pd.read_csv(csv,usecols=ctu)
    index = cas.Town[cas.Town == town].index.tolist()[0]
    named = cas.loc[index, 'Country']
    print(named)

相关问题