【发布时间】:2019-04-17 03:22:51
【问题描述】:
我有一个熊猫数据框,每天一行,还有一些布尔列。我想将它们转换为一个 DataFrame,其中包含这些列为 True 的 ranges。
一个开始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,此 DataFrame 的列为 True。
我在这个例子中寻找的输出是这个 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 式的优雅方式来执行此操作 - 甚至可能是 pandas 函数?
【问题讨论】:
-
np.where(indic[:-1]!=indic[1:]) 用于范围的结束,模拟用于开始。我能在现场想出的最好的。让我们看看是否有人有更好的想法。
标签: python pandas date datetime