简体   繁体   English

熊猫数据框:如果时间戳相同,则传播True值

[英]Pandas dataframe: propagate True values if timestamp is identical

Best described by an example. 最好用一个例子来描述。 Input is 输入为

   ts    val
0   10  False
1   20   True
2   20  False
3   30   True
4   40  False
5   40  False
6   40  False
7   60   True
8   60  False

desired output is 所需的输出是

   ts    val
0   10  False
1   20   True
2   20   True
3   30   True
4   40  False
5   40  False
6   40  False
7   60   True
8   60  True

The idea is as follows: if we see at least one True value inside the same ts cluster(ie same ts value), make all other values True that have the exact same timestamp. 这个想法如下:如果我们在相同的ts群集中看到至少一个True值(即,相同的ts值),则使所有其他具有完全相同时间戳的True为真。

You can use groupby on column 'ts', and then apply using .any() to determine whether any of val is True in the cluster/group. 您可以在“ ts”列上使用groupby ,然后使用.any()进行apply以确定集群/组中val任何一个是否为True

import pandas as pd

# your data
# =====================
print(df)

Out[58]: 
   ts    val    data
0  10  False  0.3332
1  20   True -0.6877
2  20  False -0.6004
3  30   True  0.1922
4  40  False  0.2472
5  40  False -0.0117
6  40  False  0.8607
7  60   True -1.1464
8  60  False  0.0698


# processing
# =====================
# as suggested by @DSM, transform is best way to do it
df['val'] = df.groupby('ts')['val'].transform(any)

Out[61]: 
   ts    val    data
0  10  False  0.3332
1  20   True -0.6877
2  20   True -0.6004
3  30   True  0.1922
4  40  False  0.2472
5  40  False -0.0117
6  40  False  0.8607
7  60   True -1.1464
8  60   True  0.0698

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM