【问题标题】:Get the maximum consecutive null rows in a pandas dataframe获取熊猫数据框中的最大连续空行
【发布时间】:2017-03-03 07:10:19
【问题描述】:

我有一个 DataFrame,我需要按开始和结束日期获取更大的空行序列以供进一步研究。我的索引是一个 DatatimeIndex 对象,DataFrame 如下所示:

                           C Instalation  N Serial Number D Register Read  \
Z Ts Read                                                                    
2016-12-25 00:00:00  PT0002000080299561BD   10101516046456              A+   
2016-12-25 00:15:00  PT0002000080299561BD   10101516046456              A+   
2016-12-25 00:30:00  PT0002000080299561BD   10101516046456              A+   
2016-12-25 00:45:00  PT0002000080299561BD   10101516046456              A+   
2016-12-25 01:00:00  PT0002000080299561BD   10101516046456              A+   

                    M Read D Read Unit  
Z Ts Read                               
2016-12-25 00:00:00  0,002         kWh  
2016-12-25 00:15:00  0,002         kWh  
2016-12-25 00:30:00  0,002         kWh  
2016-12-25 00:45:00  0,002         kWh  
2016-12-25 01:00:00  0,002         kWh 

NaN 值可以分散在整个 columns 数据框中,没问题。但我确实介意它们是否是连续的。在那种情况下,我想知道每一行至少有一个 NaN 值,开始和结束index 并计算两者之间的范围差。最后我想获得更大的范围。

可以这样做吗?

【问题讨论】:

  • 可能是dropna 并检查Z Ts Read 中的空白?
  • 删除 NaN 值我正在创建时间戳序列的中断,但我很难获得 delta 时间.. :/
  • 你能举例说明输出的样子吗?我无法理解您所说的按开始和结束日期排列更大的空行序列是什么意思。
  • 谢谢@pansen。我已经编辑了这个问题。没事吧?

标签: python python-3.x pandas


【解决方案1】:

不确定我是否理解 Q 100% 但也许这就是你想要的:

df = pd.DataFrame({"a": [1, 2, 3, np.nan, np.nan, np.nan, 7, 8], "b": [1, 2, 3, np.nan, 5, 6, 7, 8]}

print df

     a    b
0  1.0  1.0
1  2.0  2.0
2  3.0  3.0
3  NaN  NaN
4  NaN  5.0
5  NaN  6.0
6  7.0  7.0
7  8.0  8.0

counts = df.isnull()
counts[~counts] = np.nan
print counts

    a    b
0  NaN  NaN
1  NaN  NaN
2  NaN  NaN
3  1.0  1.0
4  1.0  NaN
5  1.0  NaN
6  NaN  NaN
7  NaN  NaN

runs = counts.cumsum()
print runs

     a    b
0  NaN  NaN
1  NaN  NaN
2  NaN  NaN
3  1.0  1.0
4  2.0  NaN
5  3.0  NaN
6  NaN  NaN
7  NaN  NaN

runs.max(axis=0)

a    3.0
b    1.0
dtype: float64

【讨论】:

  • 如果这个答案没有解决您的问题,请查看this one。结合这两个想法可以解决很多问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-14
  • 2019-01-17
  • 2022-12-12
  • 2014-06-04
  • 2021-09-30
  • 2017-08-02
相关资源
最近更新 更多