我現在有代碼可以根據用戶輸入從 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}')
uj5u.com熱心網友回復:
你可以使用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,這可以是一個可接受的輸出
uj5u.com熱心網友回復:
考慮查看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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/335579.html
上一篇:VisualStudioCodeAPI密鑰欄不斷下降
下一篇:有沒有辦法使用dbftocsvpythonlibrarydbfbyethanfurman替換和修剪單個欄位中的值?
