【问题标题】:In a For-Loop: How to compare a value with values in a groupby function在 For 循环中:如何将值与 groupby 函数中的值进行比较
【发布时间】: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


【解决方案1】:

我建议您首先计算分位数,然后应用您的逻辑来获取交互变量。很少需要循环遍历 DataFrame 的行,通常有更快的方法可用。

你可以这样做:

df = pd.DataFrame({'time': time, 'id': ids, 'vec_len': vec_len, 'id': ids})
grp = df.groupby(['time', 'id'])
quantiles = grp.vec_len.quantile([.25, .75]).unstack(level=2).reset_index()
df = df.merge(quantiles, on=['time', 'id'])
df.loc[:, 'intera'] = df[['vec_len', 0.25, 0.75]].apply(
    lambda x: 1 if x[0] < x[1] or x[0] > x[2] else 0, axis=1
)

如果您不需要分位数变量,则可以直接删除它们。

【讨论】:

  • 非常感谢,为什么我不能合并两个系列?
  • 你的意思是同时合并分位数系列吗?
  • 这段代码在 quantiles = pd.merge(quant_25, quant_75, on=['time', 'id']) 处出错。 “ValueError:无法合并没有名称的系列”。
  • 在python 3.7中复制粘贴以上作品。无论如何,请尝试更新的答案。
  • 你真是太好了,非常感谢,这对你很有帮助!!下一步是在新列中配对交互 ID。如果你知道一个简单的方法?
猜你喜欢
  • 1970-01-01
  • 2017-09-17
  • 1970-01-01
  • 1970-01-01
  • 2017-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多