如果使用 python 满足条件,如何从导入的 csv 返回值?

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

我有一个两列的 csv 文件。第 1 列是字符串值,第 2 列是整数值。如果在第 1 列的字符串中找到某个术语,我想返回第 2 列中的相应值。

第 1 栏 第 2 栏
绿色 3
红色 6

如果 Col1 包含“ed”,则返回 Col2 中相应的行值,在本例中为 6。

谢谢。

import pandas as pd
# Read the CSV file into a pandas DataFrame
file_name = input("Enter file name: ")
df = pd.read_csv(file_name)
string1 = input("Enter search term: ")
#check if each element in the DataFrame contains the partial string
matches = df.apply(lambda col: col.astype(str).str.contains(string1, case=False))
#get the row and column indices where the partial string matches
rows, cols = matches.values.nonzero()
for row, col in zip(rows, cols):
    print(f"Match found at Row: ", row)
python pandas dataframe csv
1个回答
0
投票

试试这个:

import pandas as pd

# Read the CSV file into a pandas DataFrame
file_name = input("Enter file name: ")
df = pd.read_csv(file_name)
searchstring = input("Enter search term: ")

# Search for 'green' in Col1 and return the corresponding value in Col2
result = df.loc[df['Col1'] == searchstring, 'Col2'].values

if len(result) > 0:
    print("The corresponding value of Col2 for your search in Col1 is:", result[0])
else:
    print("No corresponding value found for %s in Col1.", searchstring)

# Read the CSV file into a DataFrame
df = pd.read_csv('your_csv_file.csv')

# Search for 'green' in Col1 and return the corresponding value in Col2
result = df.loc[df['Col1'] == 'green', 'Col2'].values

if len(result) > 0:
    print("The corresponding value of Col2 for your searchstring in Col1 is:", result[0])
else:
    print("No corresponding value found for your search string in Col1.")
© www.soinside.com 2019 - 2024. All rights reserved.