Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python打印列=X,行=Y的值_Python_Pandas - Fatal编程技术网

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

Python打印列=X,行=Y的值,python,pandas,Python,Pandas,我对使用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”

我对使用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")

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

如果列中的名称是日期时间,则用于删除时间(将其设置为
00:00:00
):



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

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]

寻找细节

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

对你做事方式的微小改变会让你得到结果

步骤1:去掉00:00:00(如果只需要日期值)

第二步:你的情况有一个额外的df[]

#strip last part of the column names if column starts with 2020 
df.rename(columns=lambda x: x[:10] if x[:4] == '2020' else x, inplace=True)

current_day = datetime.date(datetime.now()).strftime("%Y-%m-%d")

relevant_value = df.loc[df['Sign'] == 'MP', current_day] #does not need df before current_day
print(relevant_value)
因为您已经在使用pandas,所以不需要导入datetime。您只需输入此项即可获得yyyy-mm-dd格式的日期

current_day = pd.to_datetime('now').strftime("%Y-%m-%d")
.floor('d')做到了!谢谢。
current_day = pd.to_datetime('now').strftime("%Y-%m-%d")