首页 > 解决方案 > 如何使用输入数字来提取数据框中的行?

问题描述

我正在根据列标题和值的输入来提取行。例如,要提取“公司”下所有“宝马”的数据行。

我可以在字符串下执行此操作(例如,在“公司”下的宝马、梅赛德斯),但不能在数字下(例如在马力下的“111”)。

我试图将“111”之类的数字更改为字符串,但无济于事。

抱歉格式不好,学习平台。

任何帮助表示赞赏!

我的部分数据是:

在此处输入图像描述

import pandas as pd
import numpy as np

df = pd.read_csv("data.csv")

column1_title = input("Hi! Please enter the first column name you are searching for: ")
column1_title = column1_title.lower()

def extract(column_check):
    if np.any(column_check == df.columns):
        column1_value = input("Thank you. Please enter the value you are looking for under this name: ")
        column1_value = str(column1_value.lower())

        if np.any(column1_value == df[column_check]):
            print("You have entered:", column1_value) #feedback.
            print(df.loc[df[column_check] == column1_value]) #M2

    elif column_check.lower() == "exit":
            print("Thank you. Goodbye.")

extract(column1_title)

标签: pythonpandas

解决方案


由于您正在让用户输入一种string类型,因此您应该Series使用以下方法将您正在检查的任何内容转换为字符串类型.astype(str)

import pandas as pd
import numpy as np

df = pd.read_csv("data.csv")

column1_title = input("Hi! Please enter the first column name you are searching for: ")
column1_title = column1_title.lower()

def extract(column_check):
    if np.any(column_check == df.columns):
        column1_value = input("Thank you. Please enter the value you are looking for under this name: ")
        column1_value = str(column1_value.lower())

        ## change this block
        if np.any(column1_value == df[column_check].astype(str)):
            print("You have entered:", column1_value) #feedback.
            print(df.loc[df[column_check].astype(str) == column1_value]) #M2

    elif column_check.lower() == "exit":
            print("Thank you. Goodbye.")

extract(column1_title)

命令行的示例输出:

>>> df = pd.DataFrame({'a':[1,2],'b':['a','b']})
>>> extract('a')
Thank you. Please enter the value you are looking for under this name: 1
You have entered: 1
   a  b
0  1  a

推荐阅读