python - 使用列和行索引作为变量填充 pandas 数据框

标签 python pandas dataframe data-munging

概览

如何使用使用列和行索引作为变量的数学来填充 pandas 数据框。

设置

import pandas as pd
import numpy as np

df = pd.DataFrame(index = range(5), columns = ['Combo_Class0', 'Combo_Class1', 'Combo_Class2', 'Combo_Class3', 'Combo_Class4'])

目标

df 中的每个单元格 = 行索引 * (列索引 + 2)

Final Objective

尝试 1

您可以使用 this生成以下代码的解决方案:

row = 0
for i in range(5):
    row = row + 1
    df.loc[i] = [(row)*(1+2), (row)*(2+2), (row)*(3+2), (row)*(4+2), (row)*(4+2), (row)*(5+2)]

尝试 2

This解决方案似乎也很相关,尽管我相信我已经读过你不应该循环访问数据帧。此外,我没有看到如何遍历行 列:

for i, j in df.iterrows(): 
    df.loc[i] = i

最佳答案

您可以利用广播来获得更高效的方法:

ix = (df.index+1).to_numpy() # .values for pandas 0.24< 
df[:] = ix[:,None] * (ix+2)

print(df)

        Combo_Class0  Combo_Class1  Combo_Class2  Combo_Class3  Combo_Class4
0             3             4             5             6             7
1             6             8            10            12            14
2             9            12            15            18            21
3            12            16            20            24            28
4            15            20            25            30            35

关于python - 使用列和行索引作为变量填充 pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56407190/

相关文章:

Python float 精度 float

python - 有什么办法可以恢复到原来的功能吗?

python - 在 Python 中使用 0xFFFFFFFF 掩码检测 int32 溢出?

python - 在 Pandas 数据框中相互获取最近点

python - 根据多个条件进行过滤的最佳方法?

r - 使用另一个条件过滤某些值和多个先前行

python - AWS Lambda 和 MySQL 连接处理

python - 为什么 Pandas 绘制索引值 (x_ticklabels) 不正确?

python - 多索引合并返回空 df 但连接应该有效

python - 将数组的 Python 字典转换为数据框