pandas :将多行数据添加到单行的额外列中 [英] Pandas: Adding data from multiple rows into extra columns for a single row

查看:62
本文介绍了 pandas :将多行数据添加到单行的额外列中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的熊猫数据框:

I have a pandas dataframe like this:

id  value
1   25
2   40
3   30

理想情况下,我想将其转换为此:

Ideally I would like to convert it to this:

id value value_2  value_3
1   25    40       30
2   40    25       30
3   30    25       40

上述对话的逻辑是,添加了另外两个包含其他ID值的列.

The logic behind the above conversation is that 2 extra columns containg the values for the other ids are added.

在第一行(id = 1)中,value_2 = id = 2的值,value_3 = id = 3的值.

In the first row (id=1), value_2 = the value of the id=2, and value_3 = the value of id = 3.

在第二行(id = 2)中,value_2 = id = 1的值,value_3 = id = 3的值

In the second row (id=2), value_2 = the value of id=1, value_3 = the value of id=3

在第三行(id = 3)中,value_2 = id = 1的值,value_3 = id = 2的值

In the 3rd row (id=3), value_2 = the value of id=1, value_3 = the value of id=2

有没有一种解决方案,使我可以立即更新所有行,而不必遍历每一行,获取值,然后更新其他行的数据框(一次更新一行).还是上述挑战最简单的解决方案是什么?

Is there a solution that allows me update all rows at once without having to iterate over each row, getting the value and then updating the dataframe of the other rows (one row at the time). Or what is the easiest solution to above challenge?

推荐答案

IUUC,您可以执行以下操作:

IUUC, you could do the following:

# create array (repeat of value)
repeats = np.tile(df['value'].values, (len(df), 1))

# remove elements from the diagonal
m = repeats.shape[0]
data = repeats[~np.eye(len(df), dtype=bool)].reshape(m, -1)

# create new DataFrame
df2 = pd.DataFrame(data=data[:, :], columns='value_' + df['id'].astype(str)[1:])

# concat old and new data
result = pd.concat([df, df2], axis=1)

print(result)

输出

   id  value  value_2  value_3
0   1     25       40       30
1   2     40       25       30
2   3     30       25       40

这篇关于 pandas :将多行数据添加到单行的额外列中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆