I have code at the moment that prints out the rows of data from a csv based on user input, this code is displayed below:
#allows user input to select a column and then select a value from that
column data = pd.read_csv('/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pip/Locations.csv')
rowcol = 0 #the colum that is being searched is column 0 row1 =
int(input("Enter Number: ")) #enter in your first point on the map Eg
15 row2 = int(input("Enter Number: ")) #enter in your 2nd point on the
graph eg 18 result = data.iloc[[row1, row2]]
But now I want my code to also print out the rows that are between these 2 values that are entered (e.g if the user puts in 12 and 15 it prints out the rows for 12, 13, 14 and 15)
this is what I have at the moment but I'm not sure how to go further:
num_list = []
for i in range(row1 1, row2):
num_list.append(i)
print(f'Numbers between 2 points are:\n{btwpoints}')
CodePudding user response:
You could use range
:
df.iloc[range(row1, row2)]
If you need to include row2
as well:
df.iloc[range(row1, row2 1)]
You should manage obvious exceptions anyway (like row2 < row1
, or out of bounds situations).
Out of bounds situations could be mananged like this:
df.iloc[range(max(0, row1), min(df.shape[0], row2 1))]
Having row2 <= row1
will return an empty DataFrame
which can be an acceptable output
CodePudding user response:
Consider checking out convtools library:
# inputs
input_file = "tmp/input.csv"
column = "Price"
left_bound = 100
right_bound = 202
rows = (
# read csv file, use header as column names
Table.from_csv(input_file, header=True)
# cast column values to int
.update(**{column: c.col(column).as_type(int)}).into_iter_rows(dict)
)
converter = (
# this one lets the left bound in, it is to be skipped
c.drop_while(c.item(column) != left_bound)
.take_while(c.item(column) != right_bound)
.gen_converter()
)
filtered_rows = iter(converter(rows))
try:
# skipping the left bound
next(filtered_rows)
except StopIteration:
print("no rows")
else:
for row in filtered_rows:
print(row)