在此處輸入圖片說明
我想使用 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']
uj5u.com熱心網友回復:
這可以根據需要提取行
# 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']
uj5u.com熱心網友回復:
您可以先宣告一個串列,然后撰寫一個回圈,該回圈將遍歷您需要的值的行。每次迭代后,您都可以將該值附加到串列中。完成回圈后,您將獲得所需的提取值。
list = []
for i,j in range of(3,10):
list.append(sheet.cell(row=i, col=j).value = list[i][j])
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/349351.html
下一篇:如何編輯串列中的字串/網址?
