我有一个熊猫数据框,每天一行,还有一些布尔列。我想将它们转换成一个数据帧,其中包含范围,其中这些列是真的。你知道吗
启动DF的示例:
import pandas as pd
t = True
f = False
df = pd.DataFrame(
{'indic': [f, f, t, t, t, f, f, f, t, f, f, t, t, t, t]},
index=pd.date_range("2018-01-01", "2018-01-15")
)
print(df)
indic
2018-01-01 False
2018-01-02 False
2018-01-03 True
2018-01-04 True
2018-01-05 True
2018-01-06 False
2018-01-07 False
2018-01-08 False
2018-01-09 True
2018-01-10 False
2018-01-11 False
2018-01-12 True
2018-01-13 True
2018-01-14 True
2018-01-15 True
此数据帧的列在2018-01-03到2018-01-05期间为真,然后在2018-01-09期间为真(仅一天),然后在2018-01-12到2018-01-15期间为真。你知道吗
我在这个例子中寻找的输出是这个DF(日期对象而不是字符串也可以,甚至是首选):
desired_result = pd.DataFrame({
'from': ["2018-01-03", "2018-01-09", "2018-01-12"],
'to': ["2018-01-05", "2018-01-09", "2018-01-15"]
})
print(desired_result)
from to
0 2018-01-03 2018-01-05
1 2018-01-09 2018-01-09
2 2018-01-12 2018-01-15
作为一个扩展,在后续步骤中,我希望这适用于多个列,例如:
df = pd.DataFrame(
{
'indic_A': [f, f, t, t, t, f, f, f, t, f, f, t, t, t, t],
'indic_B': [f, f, f, f, f, f, f, f, t, t, t, t, t, f, f]
},
index=pd.date_range("2018-01-01", "2018-01-15")
)
desired_result = pd.DataFrame({
'from': ["2018-01-03", "2018-01-09", "2018-01-12", "2018-01-09"],
'to': ["2018-01-05", "2018-01-09", "2018-01-15", "2018-01-13"],
'what': ["indic_A", "indic_A", "indic_A", "indic_B"]
})
print(desired_result)
from to what
0 2018-01-03 2018-01-05 indic_A
1 2018-01-09 2018-01-09 indic_A
2 2018-01-12 2018-01-15 indic_A
3 2018-01-09 2018-01-13 indic_B
有没有一个Python,优雅的方式来做这件事-也许甚至熊猫功能?你知道吗
首先使用^{} 进行重塑,然后按^{} 为唯一组创建辅助列,按^{} 仅过滤} 和^{} 聚合^{} :
True
,并按函数^{你可以试试
pd.DataFrame.shift
先做两列新的上下移动
而
df
将是这里的想法是
所以我们使用这个技巧
代码:
然后我们检查
start_date_list
然后我们检查
end_date_list
最后一个日期不会从True变为False,因此我们需要手动添加它。你知道吗
相关问题 更多 >
编程相关推荐