我现在有代码,根据用户输入从csv中打印出数据行,这段代码如下所示:
#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]]
但现在我希望我的代码也打印出这两个输入值之间的行(例如,如果用户输入12和15,它打印出12,13,14和15的行)
这是我目前所拥有的,但我不确定如何进一步:
num_list = []
for i in range(row1+1, row2):
num_list.append(i)
print(f'Numbers between 2 points are:n{btwpoints}')
您可以使用range
:
df.iloc[range(row1, row2)]
如果您还需要包含row2
:
df.iloc[range(row1, row2 + 1)]
你应该管理明显的异常(如row2 < row1
,或越界的情况)。
越界情况可以这样处理:
df.iloc[range(max(0, row1), min(df.shape[0], row2+1))]
使用row2 <= row1
将返回一个空的DataFrame
,这可以是一个可接受的输出
考虑查看convtools库:
# 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)