使用 Python 中的列键和行键创建二维数组

Create 2-d array with column keys and row keys in Python

我正在尝试在 Python 中创建此数据结构: 2-d array structure

必须有列键行键,我稍后会用到。 列键和行键是随机数。

现在我有这个代码:

import random

cols, rows = 5, 5 
Matrix = [[0 for x in range(cols)] for y in range(rows)]

set_col = 0
for row in Matrix:
    row[set_col] = random.randint(1,2)

columnKeys = random.sample(range(1,5), 4)
Matrix[0] = columnKeys

for row in Matrix:
    print(row)

输出:

[3, 1, 2, 4]
[2, 0, 0, 0, 0]
[1, 0, 0, 0, 0]
[2, 0, 0, 0, 0]
[1, 0, 0, 0, 0]

这不是我想要的。现在每个单元格值都为零。但稍后它会有一些相关数据,我将使用这些数据以及 corresponding 行和列键。我不知道如何正确组织此数据结构,因此我可以使用具有相应 row/column 键的单元格值。


怎么做 没有 PandasNumpy 所以我可以使用列键和行键?

import random

COLS, ROWS = 5, 5 
Matrix = [[0 for x in range(COLS)] for y in range(ROWS)]

set_col = 0
for row in Matrix:
    row[set_col] = random.randint(1,2)

columnKeys = random.sample(range(1,5), 4)
Matrix[0] = [0] + columnKeys

for row in Matrix:
    print(row)

输出

[0, 3, 1, 2, 4]
[2, 0, 0, 0, 0]
[1, 0, 0, 0, 0]
[2, 0, 0, 0, 0]
[1, 0, 0, 0, 0]

这取决于你想要什么。

最好的方法可能是使用嵌套列表,而是使用字典。既然你提到了 pandas,pandas DataFrame 对象有一个 to_dict 函数,可以将 DataFrame 转换成字典,并且有几个选项取决于你喜欢什么。

我从您的示例中看出您正在尝试创建具有重复索引的数据结构。这里最好的选择可能是使用 运行ning df.to_dict("split").

创建的结构

假设您的 DataFrame (df) 如下所示:

      3  1  2  4
   2  0  0  0  0
   1  0  0  0  0
   2  0  0  0  0
   1  0  0  0  0

运行 `df.to_dict("split") 然后会这样做:

d = df.to_dict("split")
{
  'columns': [3, 1, 2, 4],
  'data': [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
  'index': [2, 1, 2, 1]
}

在这种情况下以及@Makiflow 显示的情况下访问数据很棘手。即使在 Pandas 中,Dataframe 上有重复的索引或列也会使操作更有趣。在这种情况下,selecting df['data'][3][1] 选择 data 键包含的第三个列表中的第二个元素。这实际上是 select 矩阵的第 4 行和第 2 列。如果您希望能够通过列 name 引用项目,您必须多做一些工作。

你可以 运行 col_num = d['columns'].index(3) 这会给你元素的索引值 3,但是 d['index'].index(2) 总是会给你 0,即使你想select 2 at index 3. 那是因为 index() returns 第一个符合条件的值的索引。您当然可以通过 (col,row) 索引元组简单地 select,但这违背了将列名和索引值放在首位的目的。

如果你想在没有pandas的情况下生成这个结构,你可以运行: 列、行 = 5、5 columns = [random.randint(0,COLS) for _ in range(COLS)] rows = [random.randint(1,2) for _ in range(ROWS)]

d = {"columns": columns,
     "index":   rows,
     "data":    [[0 for _ in range(COLS)] for _ in range(ROWS)]
    }

恕我直言 - 更好的解决方案实际上是强制您的数据结构具有唯一的索引和列值。 to_dict()的默认输出会输出一个非常简单的字典:

d = df.to_dict() # also the same as df.to_dict("dict")
{
  1: {1: 0, 2: 0}, 
  2: {1: 0, 2: 0}, 
  3: {1: 0, 2: 0}, 
  4: {1: 0, 2: 0}
}

在此配置中,字典的每个键都是一列的名称。这些键中的每一个都指向另一个表示该列中信息的字典——每个键都是一个索引值,后跟值。

这可能是最直观的感觉,因为如果您想在索引 named 1 处获取列 named 3 的值,你会这样做:

   d = df.to_dict()
   d[3][1]
   # 0

您无需使用 Pandas 即可非常简单地创建此数据结构:

COLS, ROWS = 5,5 
rows = [i for i in range(ROWS)]
columns = [i for in range(COLS)]
{c : {i:0 for i in rows} for c in columns}
# {
#  0: {0: 0, 1: 0, 2: 0, 3: 0, 4: 0},
#  1: {0: 0, 1: 0, 2: 0, 3: 0, 4: 0},
#  2: {0: 0, 1: 0, 2: 0, 3: 0, 4: 0},
#  3: {0: 0, 1: 0, 2: 0, 3: 0, 4: 0},
#  4: {0: 0, 1: 0, 2: 0, 3: 0, 4: 0}
# }

这真的取决于你拥有的constraints/requirements。