[英]How to extract a particular set of values from excel file using a numerical range in python?
[英]How to extract values in a specific row range from Excel with Python
我想使用 Python 在 Excel 中打印出與特定月份相對應的所有行值。 請看圖片。
如果我使用函數將“2021.10”放在函數值中,我想要值 [2021.10.03”、“2021.10.03”、“2021.10.03”、“2021.10.03”、“2021.10.03”、“無” 2021.10.15", "2021.10.15", None] 要輸入到列表中。
簡單地說,如果我將值“2021.10”放入函數中,我想從 A 列的第 5 行到第 13 行中提取值。
我該怎么辦?
我現在正在閱讀 openpyxl 中的表格。
import openpyxl as oxl load_excel = oxl.load_workbook('C:/Users/Homework.xlsx',data_only = True) load_sheet = load_excel['Sheet']
這可以根據需要提取行
# dataframe from the excel file
A B C
0 2021.09.23 E 1
1 2021.09.23 A 1
2 2021.09.23 E 1
3 None None 3
4 2021.10.03 A 1
5 2021.10.03 A 2
6 2021.10.03 B 2
7 2021.10.03 E 1
8 2021.10.03 A 1
9 None None 7
10 2021.10.15 A 2
11 2021.10.15 B 3
12 None None 5
13 2021.11.03 C 2
14 2021.11.03 B 1
15 2021.11.03 F 2
def extract(df, value):
df = df.reset_index() # to make index column
first_index = df[(df['A'].str.startswith(value))].iloc[0]['index'] # to get index of first 2021.10 value
last_index = df[(df['A'].str.startswith(value))].iloc[-1]['index'] # to get index of last 2021.10 value
sub_df = df.iloc[first_index:last_index+1,] # to make dataframe from first index to last index
for i, row in df[last_index+1:].iterrows():
# to add all None right after the last value
if row['A'] == 'None':
sub_df = sub_df.append(row)
else:
break
print(sub_df['A'].to_list())
import pandas as pd
df = pd.read_excel('C:/Users/Homework.xlsx') # I read xlsx file using pandas instead of `openpyxl`
extract(df, '2021.10')
這將由函數打印:
['2021.10.03', '2021.10.03', '2021.10.03', '2021.10.03', '2021.10.03', 'None', '2021.10.15', '2021.10.15', 'None']
您可以先聲明一個列表,然后編寫一個循環,該循環將遍歷您需要的值的行。 每次迭代后,您都可以將該值附加到列表中。 完成循環后,您將獲得所需的提取值。
list = []
for i,j in range of(3,10):
list.append(sheet.cell(row=i, col=j).value = list[i][j])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.