【问题标题】:Python: Accessing cell value in panda and performing mathematical operationsPython:在熊猫中访问单元格值并执行数学运算
【发布时间】:2019-03-23 18:33:55
【问题描述】:

我有一个 4 行 4 列的 excel 文件,列标签为 1,2,3,4

               1      2        3       4
 Row   1      12      10       7       6
 Row   2      16      22       9      18
 Row   3      26      10      10       5
 Row   4      24       5      17       1

我希望访问第 3 列第 1 行整数值和第 4 列第 1 行整数值以检查两个单元格相加是否等于 50。在这种情况下,任何 (p,q,r) 组合都应添加 (row q, col p) 和 (row r, col p) 值,如果值 = 50,则返回 (p,q,r) 作为组合。

在这种情况下,输出应该是:(1,3,4)

import pandas as pd

import numpy as np

a = [1,2,3,4]

df = pd.read_excel('example.xlsx', sheetname='Sheet1')

combo = [(p,q,r) for p in a for q in a for r in a 
                  if (df.iloc[q,p] + df.iloc[r,p] = 50)]

print (combo)

更新:

尝试过,但稍作修改,即我正在表的列之间进行计算:

组合 (1,3,4) 现在应该在以下单元格中查找值

(1,1) (1,3) (1,4)

(3,1) (3,3) (3,4)

(4,1) (4,3) (4,4)

import numpy as np

import pandas as pd

df = pd.read_excel('example.xlsx', sheetname='Sheet1')

df.index = list(range(1, df.shape[1] + 1))
df.columns = list(range(1, df.shape[1] + 1))

combo = [(p,q,r) for p in df.columns for q in df.columns for r in df.columns 
          if q > p and r > q and r > p
          and df.loc[p,p] - df.loc[p,q] == df.loc[q,p] - df.loc[q,q]]

我收到以下错误

ValueError:长度不匹配:预期轴有 3 个元素,新值有 4 个元素

【问题讨论】:

  • 我很难理解这个问题。你能给出你的数据(子集)并显示预期的输出吗?
  • 已对问题进行了澄清。谢谢。

标签: python excel pandas


【解决方案1】:

首先,确保您的 DataFrame 索引和列都是整数索引,从 1 开始(与您的输入数据保持一致):

df.index = list(range(1, df.shape[0] + 1))
df.columns = list(range(1, df.shape[1] + 1))

接下来,你的列表理解是正确的:

[(p,q,r) for p in df.index for q in df.index for r in df.columns 
 if df.loc[q,p] + df.loc[r,p] == 50]

# Output
[(1, 3, 4), (1, 4, 3)]

【讨论】:

  • 请注意,这仅在索引和列具有相同名称时才有效。即,如果列确实是 [1, 2, 3, 4] 但索引通常为基于 [0, 1, 2, 3] 的 0,则会出现错误。
  • True,因此使用从 1 开始的整数索引覆盖索引和列的预处理步骤。
  • @PeterLeimbigler 对我遇到的错误有任何想法。更新了问题。
  • 您错误地复制了两个重新索引行中的第一行。 df.index = list(range(1, df.shape[1] + 1)) 应该是 df.index = list(range(1, df.shape[0] + 1))
猜你喜欢
  • 2019-01-31
  • 2021-09-06
  • 2017-01-14
  • 2017-05-03
  • 1970-01-01
  • 1970-01-01
  • 2016-04-22
  • 1970-01-01
  • 2021-10-13
相关资源
最近更新 更多