Home > front end >  Python how to select specific cells on excel with pandas
Python how to select specific cells on excel with pandas

Time:11-14

I have an excel here as shown in this picture:

enter image description here

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:

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. And I want to store these values in my python array below:

mynumbers= []

but I am not sure how should I do it, can you please help me?

CodePudding user response:

You should consider slicing your dataframe and then using .values to story them. If you want them as a list, then you can use 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

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

Assigning the following values to mynumbers:

[11,8]

CodePudding user response:

A first step would be to convert your Date column to datetime objects

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

  • Related