简体   繁体   English

Python 如何使用 pandas 在 excel 上使用 select 特定单元格

[英]Python how to select specific cells on excel with pandas

I have an excel here as shown in this picture:我这里有一个 excel,如图所示:

在此处输入图像描述

I am using pandas to read my excel file and it is working fine, this code below can print all the data in my excel:我正在使用 pandas 读取我的 excel 文件并且它工作正常,下面的代码可以打印我的 excel 中的所有数据:

import pandas as pd

df = pd.read_csv('alpha.csv')

print(df)

I want to get the values from C2 cell to H9 cell which month is October and day is Monday only.我想获取从 C2 单元格到 H9 单元格的值,哪个月份是十月,哪一天是星期一 And I want to store these values in my python array below:我想将这些值存储在下面的 python 数组中:

mynumbers= []

but I am not sure how should I do it, can you please help me?但我不确定我该怎么做,你能帮帮我吗?

You should consider slicing your dataframe and then using .values to story them.您应该考虑对 dataframe 进行切片,然后使用.values来描述它们。 If you want them as a list, then you can use to_list() :如果您希望将它们作为列表,则可以使用to_list()

First transform the Date column to a datetime:首先将日期列转换为日期时间:

df['Date'] = pd.to_datetime(df['Date'],dayfirst=True,infer_datetime_format=True)

Then, slice and return the values for the Column Number 2然后,切片并返回列Number 2的值

mynumbers = df[(df['Date'].dt.month == 10) & \
               (df['Date'].dt.weekday == 0)]['Column 2'].values.tolist()

Assigning the following values to mynumbers :将以下值分配给mynumbers

[11,8]

A first step would be to convert your Date column to datetime objects第一步是将 Date 列转换为 datetime 对象

import datetime

myDate = "10-11-22"
myDate = datetime.datetime.strptime(myDate, '%d-%m-%y')

Then using myDate.month and myDate.weekday() you can select for mondays in October然后使用 myDate.month 和 myDate.weekday() 你可以在 10 月的星期一使用 select

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM