【问题标题】:How can i create a new column that inserts the cell value of grouped column 'ID' (in time) when 'interaction' is 1当“交互”为 1 时,如何创建一个插入分组列“ID”(及时)的单元格值的新列
【发布时间】:2020-03-15 20:26:37
【问题描述】:

我有三个相关的列:时间、id 和交互。 如何在给定时间窗口的“交互”列中创建一个 ID 值为“1”的新列?

应该是这样的:

time   id   vec_len  quadrant   interaction    Paired with

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    [2778, 4228]
2    3229    -0.3   2   0
2    4228    -0.8   5   1    [2778, 3229]
2    2778   -0.6    5   1    [4228, 3229]
3    4228    0.2    0   0
3    3271    0.1    6   0
3    4228    -0.7   5   1    [3271]
3    3229    -0.3   2   0
3    3271    -0.8   5   1    [4228]

感谢您的帮助!!

【问题讨论】:

  • 如何使用 id 值创建新列”是什么意思?您想向此数据框添加一列还是您的目标是什么?
  • 我试图在标题中澄清。所以在时间块 x 中,当 'interaction' 为 1 时,将在该时间块中也有 '1' 的其他 id 的单元格值插入到新列中。
  • 您能举个例子吗?所有 id 都已经在 id 列中。如果interaction1None,那么您想要另一列id_interaction 具有id
  • 抱歉,不够清楚。我试试。因此,基于时间块 2,我们有 3 个 ID,在“交互”列中状态为 1。在一个新的“配对”列中,我想列出该时间块中的 ID 在列交互中也有 1。
  • 在这种情况下,3229 在新列中获取值 2778 和 4228,因为它们在时间块 2 中也有 'interaction'==1。

标签: python pandas dataframe if-statement iteration


【解决方案1】:
import numpy as np

# initialize dict for all time blocks
dict_time_ids = dict.fromkeys(df.time.unique(), set())

# populate dictionary with ids for each time block where interaction == 1
dict_time_ids.update(df.query('interaction == 1').groupby('time').id.apply(set).to_dict())

# make new column with set of corresponding ids where interaction == 1
df['paired'] = np.where(df.interaction == 1, df.time.apply(lambda x: dict_time_ids[x]), set())

# remove the id from the set and convert to list
df.paired = df.apply(lambda x: list(x.paired - {x.id}), axis=1)

# Out:
    time    id  interaction        paired
0      1  3271            0            []
1      1  3229            0            []
2      1  4228            0            []
3      1  2778            0            []
4      2  4228            0            []
5      2  3271            0            []
6      2  3229            1  [2778, 4228]
7      2  3229            0            []
8      2  4228            1  [2778, 3229]
9      2  2778            1  [4228, 3229]
10     3  4228            0            []
11     3  3271            0            []
12     3  4228            1        [3271]
13     3  3229            0            []
14     3  3271            1        [4228]

【讨论】:

    猜你喜欢
    • 2023-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多