Python打印列=X,行=Y的值

2024-05-29 06:01:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我对使用python和pandas比较陌生,我正在尝试使用python获取excel工作表中单元格的值。更糟糕的是,我使用的excel工作表没有正确的列名

以下是数据帧的外观:

Sign       Name       2020-09-05 2020-09-06 2020-09-07
JD         John Doe   A          A          B
MP         Max Power  B          B          A

我要做的是打印“cell”的值,其中列标题是当前日期,符号是“MP”

到目前为止,我尝试的是:

import pandas as pd
from datetime import datetime

time=datetime.now()
relevant_sheet = time.strftime("%B" " %y")
current_day = time.strftime("%Y-%m-%d")

excel_file = pd.ExcelFile('theexcelfile.xlsx')
df = pd.read_excel(excel_file, relevant_sheet, skiprows=[0,1,2,3]) # I don't need these
relevant_value = df.loc[df['Sign'] == "MP", df[current_day]]

这给了我一个当前_日的关键错误:

KeyError: '2020-09-07'

要完全披露我正在使用的真实数据帧的任何可能问题:如果我只是打印数据帧,我会得到如下列:

2020-09-01 00:00:00

这就是为什么我也尝试:

current_day = time.strftime("%Y-%m-%d 00:00:00")

当然,我也“手动”尝试了各种日期格式,但都没有用。我是不是完全错了?这是不是在骗我


Tags: 数据importpandasdfdatetimetimempcurrent
3条回答

如果列中的名称是datetimes,则使用^{}作为删除时间(将其设置为00:00:00):

current_day = pd.to_datetime('now').floor('d')
print (current_day)
2020-09-07 00:00:00

relevant_value = df.loc[df['Sign'] == "MP", current_day]

如果列中的名称是字符串格式的日期时间,请使用:

relevant_value = df.loc[df['Sign'] == "MP", current_day]

如果有python日期:

current_day = pd.to_datetime('now').date()
print (current_day)
2020-09-07

relevant_value = df.loc[df['Sign'] == "MP", current_day]

使用df.filter筛选相关列

通过提取今天的日期并将其转换为字符串来获取相关列

继续并查询Sign以查找MP

df.loc[df['Sign']=='MP',(dt.date.today()).strftime('%Y-%m-%d')]

您只需要传递列名,而不是df[col\u name]

查看.loc[]了解详细信息

df.loc[df['Sign'] == "MP", current_day]

相关问题 更多 >

    热门问题