[英]Trying to print specific values from a column .csv file in python
I'm trying to get and print all the values (integers) from a column that matches with an specific input.我正在尝试从与特定输入匹配的列中获取并打印所有值(整数)。 The lenght of the input must be between 3 and 15, as shown below:
输入的长度必须在 3 到 15 之间,如下图:
import pandas as pd
file = pd.read_csv('filename.csv', encoding="ISO-8859-1", engine='python', sep=';')
def codechoice():
codeNum = int(input("What's the code: "))
if (len(str(codeNum))) > 3 and (len(str(codeNum))) < 15:
result = file[file['Column 2'].str.contains(codeNum)]
print(result)
codechoice()
It's showing the result as expected, but also it's showing all other columns from the csv file of that specific input.它按预期显示结果,但也显示该特定输入的 csv 文件中的所有其他列。 Also, if I input, lets say, "100", it is printing all the ocurrencies that has "100" in its length.
另外,如果我输入“100”,它会打印所有长度为“100”的货币。
The question is: How do I delimit that I want only one specific Column?问题是:我如何界定我只想要一个特定的列?
Example, if entering the input I just wanted to print the columns 4 and 5?例如,如果输入我只想打印第 4 列和第 5 列? And how to correct the length error?
以及如何纠正长度错误?
thank you.谢谢你。
I added some coding to present with some example data so you might need to tweek it a little to match your own data set, but this will return all the rows that match a zip_code that you enter as a df我添加了一些编码来呈现一些示例数据,因此您可能需要稍微调整一下以匹配您自己的数据集,但这将返回与您作为 df 输入的 zip_code 匹配的所有行
data = {
'State' : ['NC', 'SC', 'NC', 'SC'],
'ZipCode' : [28215, 10101, 28201, 10111]
}
df = pd.DataFrame(data)
def codechoice():
codeNum = int(input("What's the code: "))
if (len(str(codeNum))) > 3 and (len(str(codeNum))) < 15:
result = df.loc[df['ZipCode'] == int(codeNum)]
return result
zip_choice_df = codechoice()
zip_choice_df
From there if you wanted to only limit the return to a specific set of columns you can take another step by adding a df = df[[]] to limit to the specific columns like so:从那里,如果您只想将返回限制为一组特定的列,您可以通过添加 df = df[[]] 来限制特定列,如下所示:
data = {
'State' : ['NC', 'SC', 'NC', 'SC'],
'Country' : ['USA', 'USA', 'USA', 'USA'],
'ZipCode' : [28215, 10101, 28201, 10111]
}
df = pd.DataFrame(data)
def codechoice():
codeNum = int(input("What's the code: "))
if (len(str(codeNum))) > 3 and (len(str(codeNum))) < 15:
result = df.loc[df['ZipCode'] == int(codeNum)]
return result
zip_choice_df = codechoice()
zip_choice_df = zip_choice_df[['State', 'Country']]
zip_choice_df
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.