使用python获取基于另一列的列值

2024-04-25 19:26:12 发布

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

如何在日期介于2015-01-01和2015-03-01之间时获取列值,或者为2015-01-01和2015-03-01之间的日期创建所有列的新数据框

这是我当前的代码:

 from datetime import date
 from nsepy import get_history
 sbin = get_history(symbol='SBIN',
                       start=date(2015,1,1),
                       end=date(2015,1,10))

这是输入数据:

Symbol Series  Prev Close    Open    High     Low   Last   Close  \
Date
2015-01-01   SBIN     EQ      311.85  312.45  315.00  310.70  314.0  314.00
2015-01-02   SBIN     EQ      314.00  314.35  318.30  314.35  315.6  315.25
2015-01-05   SBIN     EQ      315.25  316.25  316.80  312.10  312.8  312.75
2015-01-06   SBIN     EQ      312.75  310.00  311.10  298.70  299.9  299.90
2015-01-07   SBIN     EQ      299.90  300.00  302.55  295.15  301.4  300.15

我有一个DataFarme,它有很多年的数据,我经常需要绘制它的小样本(基于日期的不同样本),我需要一个函数来根据一些日期分割我的数据帧。例如,一个新的数据帧具有相同的列,但仅适用于这些日期2015-01-01-2015-03-01


Tags: 数据代码fromimportclosegetdatetimedate
2条回答

我不确定我完全理解你的问题,但我是这样解释的:

场景1:您只需要获取数据帧中日期列位于某个范围之间的行。你可以用熊猫来做这个测向位置这样地。。。你知道吗

#Create a dataframe similar to yours
d = pd.DataFrame({'date': [datetime.date(2015,01,01), datetime.date(2015,01,02), datetime.date(2015,01,05), datetime.date(2015,01,06), datetime.date(2015, 01, 07)], 'open': [1, 2, 3, 4, 5]})

new_df = d.loc[(d['date'] >= datetime.date(2015,01,01)) & (d['date'] < datetime.date(2015,01,05))]

返回日期介于2015-01-01和2015-01-05(不包括05)之间的行。你知道吗

场景2:您希望根据上述日期条件获取特定列的值。你可以这样做。。。你知道吗

another_df = d.loc[(d['date'] >= datetime.date(2015,01,01)) & (d['date'] < datetime.date(2015,01,05)), 'open']

我们只需根据日期条件指定要从中获取信息的列名,在本例中是“open”列。你知道吗

你可以对日期进行比较,就像对其他事情一样

# This will be true for every row that is true for both of these comparisons
idx = (sbin.index >= date(2015,1,1)) * (sbin.index <= date(2015,3,1))

sbin.iloc[idx].loc[:, ('Open', 'Close')]
new_sbin = sbin.iloc[idx]

相关问题 更多 >