尝试获取与另一个元素匹配的行的索引

问题描述 投票:0回答:1

我正在尝试获取我的 df 上特定原始数据的索引(作为积分),我的 df 是多索引,因为我连接了两个数据帧(日期数据帧和价格数据帧)

dataframe = pd.concat([date_df, prices_df], axis='columns')

看起来和这个很像

 Date      Price

index                    0     0.0000
0      2024-04-30 10:21:43  3333.3625
1      2024-04-30 10:23:43  3288.2678
2      2024-04-30 10:25:43  3293.0690
3      2024-04-30 10:27:43  3280.0830
4      2024-04-30 10:29:43  3273.8162
5      2024-04-30 10:31:43  3268.4622
6      2024-04-30 10:33:43  3262.4119
7      2024-04-30 10:35:43  3256.7690
8      2024-04-30 10:37:43  3252.1814

另外,我想做的是用 now 对象更新它(这需要是 pd.query 的字符串)

now = datetime.now().replace(microsecond=0, second=7)
now = str(now)
print(now)

> 2024-04-30 12:21:07

所以我有一些选择,我尝试过 pd.query() 像:

row_index = dataframe.query(dataframe['Date'] == str(now)).index[0]

得到:


row_index = dataframe.query(dataframe['Date'] == str(now)).index\[0]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "C:\\Users\\Angel\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\pandas\\core\\frame.py", line 4437, in query
raise ValueError(msg)
ValueError: expr must be a string to be evaluated, \<class 'pandas.core.series.Series'\> given

尝试过 dataframe.index() 像:

row_index = dataframe.index[dataframe['Date'] == str(now)].tolist()

得到:

[]

尝试过 dataframe.index.get_loc() 像:

row_index = data.index.get_loc(dataframe['Date'] == now)

得到:

pandas.errors.InvalidIndexError: index    False
0        False
1        False
2        False
3        False
...
43196    False
43197    False
43198    False
43199    False
43200    False
Name: Date, Length: 43202, dtype: bool
Index: []

row_index = dataframe.index.get_loc(dataframe.loc[data.iloc[:, 0] == str(now)])

得到:

pandas.errors.InvalidIndexError: Empty DataFrame
Columns: [Date, Price]
Index: []

它说数据框是空的

我尝试用以下方法解决它:

from pandas.errors import EmptyDataError
try:


    if dataframe.empty:
        raise EmptyDataError

except EmptyDataError:
print('dataframe is empty')

我只想获取索引作为现在字符串的整数,该字符串与我的数据框中的日期行匹配

如果有人可以提供反馈并更好地知道如何解决它,我非常感谢您的帮助。

your text

预期输出:

>5980 

例如

python pandas dataframe datetime
1个回答
0
投票

您需要确保 DataFrame 中的

Date
列的类型为
datetime
pd.to_datetime()

然后,使用

strftime
有助于确保查询格式与
datetime
保持一致。

最后,布尔索引应该按照您想要的方式工作。

data_dict = {'Date': ['2024-04-30 10:21:43', '2024-04-30 10:23:43'], 'Price': [3333.3625, 3288.2678]}
dataframe= pd.DataFrame(data_dict)
dataframe['Date'] = pd.to_datetime(dataframe['Date'])

now = datetime.now().replace(microsecond=0, second=7) 
now_str = now.strftime('%Y-%m-%d %H:%M:%S')

index_list = dataframe.index[dataframe['Date'] == now_str].tolist()
© www.soinside.com 2019 - 2024. All rights reserved.