gpt4 book ai didi

python - 将数据框中的每一列与其右侧的列相乘 Python

转载 作者:太空狗 更新时间:2023-10-30 01:36:05 26 4
gpt4 key购买 nike

我有一个大型数据框,其中包含大约 400.000 个观察值和 6.500 列。我正在寻找一种快速方法,将每一列依次与其右侧的列相乘。

示例数据框可能如下所示:

| V1  | V2  | V3  |  
----------------------
| 1 | 2 | 1 |
| 0 | 4 | 1 |
| 1 | 3 | 3 |

最后我想要这样的东西:

| V1 | V2 | V3 | V1_V2 | V1_V3 | V2_V3 |
-----------------------------------------
| 1 | 2 | 1 | 2 | 1 | 2 |
| 0 | 4 | 1 | 0 | 0 | 4 |
| 1 | 3 | 3 | 3 | 0 | 9 |

我尝试了 itertools.combinations 但它太慢了。我是 Python 的初学者,所以也许有一个我不知道的简单解决方案。

感谢您的帮助!

最佳答案

pandas 向量化运算(如乘法)本身非常高效。您可以使用类似以下的方法来利用这一点:

# Extract column names
cols = df.columns.tolist()

# Generate all adjacent pairs, including the circular one
cols_to_create = [(cols[i], cols[i+1]) for i in range(len(cols)-1)] \
+ [(cols[len(cols)-1], cols[0])]

# Perform multiplication on all pairs
for x, y in cols_to_create:
df[x+'_'+y] = df[x]*df[y]

关于python - 将数据框中的每一列与其右侧的列相乘 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54197268/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com