python - 如何使用输入数字来提取数据框中的行?
问题描述
我正在根据列标题和值的输入来提取行。例如,要提取“公司”下所有“宝马”的数据行。
我可以在字符串下执行此操作(例如,在“公司”下的宝马、梅赛德斯),但不能在数字下(例如在马力下的“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)
解决方案
由于您正在让用户输入一种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
推荐阅读
- javascript - 我应该做些什么来让它显示变量而不是值?
- laravel - 如何在点击时破坏 livewire 组件?
- pandas - 在 pandas 转换 lambda 函数中,如果最大为无穷大,则使用 if else 来获得第二大值
- haskell - quickCheck 命题逻辑生成器
- android - Android中不兼容的firebase库
- java - Sonarqube 问题 - 将此“尝试”更改为资源尝试。如何处理条件资源?
- arrays - 如何在swift 5中将所有元素从自定义对象收集到数组中
- javascript - 我的异步组件渲染了两次,并且期望即使使用 await 也不会等待第二次?
- node.js - MongoDB 排序/加权$或聚合查询
- html - 基于所选滑块图像的自定义页面 html