python - Pandas Dataframe - 如何将两列值堆叠到一个列表中?

标签 python pandas stack melt

我有一个包含三列的数据框(from、to、w):

      from to w
0     0   1  0.670820
1     0   5  0.612372
2     0   2  0.612372
3     0   3  0.577350
4     0   4  0.408248

如何根据给定的 id 从两列(from、to)获取列表中的值?例如,在上面的示例中,对于给定 id 0,列表将为 [1,5,2,3,4]。

请注意,id 可能出现在第 1 列或第 2 列中。在示例中,如果给定 id 为 1,则下面的预期列表将为 [2,4,0,3,5]。

     from  to   w
0     1   2  0.730297
1     1   4  0.730297
2     0   1  0.670820
3     1   3  0.516398
4     1   5  0.365148

我迭代数据框中的行以生成列表:

myarr =[]
    for index, row in dftemp1.iterrows():
        from_id = row['from']
        to_id = row['to']
        if (from_id!=target_id):
            myarr.append(from_id)
        if (to_id!=target_id):
            myarr.append(to_id)

我想知道是否有更简单的方法来实现结果。任何帮助将不胜感激。

最佳答案

使用你的第二个例子 -

df

   from  to         w
0     1   2  0.730297
1     1   4  0.730297
2     0   1  0.670820
3     1   3  0.516398
4     1   5  0.365148

您可以根据前两列中的值是否等于您的 ID 对值进行argsort

v = df.iloc[:, :-1].values

i = np.arange(len(df))[:, None]
j = np.argsort(v == 1, axis=1)   # replace `1` with your ID

v[i, j][:, 0].tolist()
[2, 4, 0, 3, 5]

关于python - Pandas Dataframe - 如何将两列值堆叠到一个列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48182939/

相关文章:

python - Pandas: reshape 数据框

python - 将时间舍入到最近的小时python

python - 如何使用 python/pandas 消除列中具有连续值的行

Python3.8 `all()` 不短路

python - 根据已过滤的 pandas 数据帧绘制定义的 x/y 范围的 pcolormesh,即使该行或列不存在于已过滤的数据帧中

c++ - 在 Stack 实现中使用哪个智能指针?

c - 用 C 将项目插入堆栈

java - `try/catch`具体是怎么工作的

python - 范围函数Python

python - ValueError : Found array with 0 feature(s) (shape=(546, 0)) 而至少需要 1