【发布时间】:2020-03-15 07:46:33
【问题描述】:
如何将一行与一组值进行比较?我正在尝试遍历分组时间窗口中的各个 ID,并将唯一 ID 与时间间隔中其他 ID 的值进行比较。条件语句只想考虑低于或高于阈值的那些,如果为 True,则在新列中附加值 1。
我有以下代码:
time = np.array([1,1,1,1,2,2,2,2,2,2,3,3,3,3,3])
ids = np.array([3271,3229,4228,2778,4228,3271,3229,3229,4228,2778,4228,3271,4228,3229,3271])
vec_len = np.array([,0.1,0.5,-0.0,0.0,0.1,-0.7,-0.3,-0.8,-0.6,0.2,0.1,-0.7,-0.3,-0.8])
quad = np.array([7,0,0,5,0,6,5,2,5,5,0,6,5,2,5])
df = pd.DataFrame({'time': time, 'id': ids, 'vec_len': vec_len, 'id': ids})
df['intera'] = np.array(0)
id_group=df.groupby(['time'])
interaction = []
for g_idx, group in id_group:
for r_idx, row in group.iterrows():
if (row['vec_len'] > group.groupby('id')['vec_len'].quantile(0.75) or row['vec_len'] <
group.groupby('id')['vec_len'].quantile(0.25)):
interaction.append('1')
谁能帮忙?
time id vec_len quadrant interaction
1 3271 0.9 7 0
1 3229 0.1 0 0
1 4228 0.5 0 0
1 2778 -0.3 5 0
2 4228 0.2 0 0
2 3271 0.1 6 0
2 3229 -0.7 5 1
2 3229 -0.3 2 0
2 4228 -0.8 5 1
2 2778 -0.6 5 1
3 4228 0.2 0 0
3 3271 0.1 6 0
3 4228 -0.7 5 1
3 3229 -0.3 2 0
3 3271 -0.8 5 1
【问题讨论】:
-
vec_len的第一个元素丢失,并且值与您的示例中的不同。vec_len[3]在代码中是-0.0,但在您的示例中是-0.3。
标签: python for-loop conditional-statements pandas-groupby conditional-operator