[英]How do you use an input number to extract rows in a dataframe?
I am extracting rows based on input of a column header and a value.我正在根据列 header 的输入和一个值来提取行。 For example, to extract data rows for all 'bmw' under 'company.
例如,要提取“公司”下所有“宝马”的数据行。
I can do this under strings (eg bmw, mercedes under 'company') but not numbers (eg '111' under horsepower).我可以在字符串下执行此操作(例如,在“公司”下的宝马、梅赛德斯),但不能在数字下(例如在马力下的“111”)。
I tried to change numbers like '111' to string but to no avail.我试图将“111”之类的数字更改为字符串,但无济于事。
Sorry for the bad formatting, learning the platform.抱歉格式不好,学习平台。
Any help is appreciated!任何帮助表示赞赏!
Part of my data is:我的部分数据是:
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)
Since you are making the user input a string
type, you should convert any Series
you are checking to a string type by using the .astype(str)
method:由于您正在让用户输入
string
类型,因此您应该使用.astype(str)
方法将您正在检查的任何Series
转换为字符串类型:
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)
Example output from the command line:来自命令行的示例 output:
>>> 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.