首页 > pandas > 在更改特定单元格后强制重新计算数据帧

在更改特定单元格后强制重新计算数据帧 (Forcing dataframe recalculation after a change of a specific cell)

2018-11-02 pandas

问题

我从一个简单的开始

df = pd.DataFrame({'units':[30,20]})

我明白了

      units
 0      30
 1      20

然后我在列中添加一行:

my_sum = df.sum()
df = df.append(my_sum, ignore_index=True)

最后,我添加一列来计算'单位'列的百分比:

df['pct'] = df.units / df.units[:-1].sum()

以此结尾:

    units   pct
 0  30     0.6
 1  20     0.4
 2  50     1.0

到目前为止一直很好 - 但现在的问题是:我想将中间数量的单位从20改为,例如,30。我可以使用这个:

df3.iloc[1, 0] = 40

要么

df3.iat[1, 0] = 40

更改单元格,但最后一行和第二列的计算值不会更改以反映它:

    units   pct
 0  30      0.6
 1  40      0.4
 2  50      1.0

如何根据特定单元格中的更改强制调整这些计算值?

解决方法

创建一个计算它的函数

def f(df):
  return df.append(df.sum(), ignore_index=True).assign(
      pct=lambda d: d.units / d.units.iat[-1])

df.iat[1, 0] = 40

f(df)

   units       pct
0     30  0.428571
1     40  0.571429
2     70  1.000000

问题

I start with a simple

df = pd.DataFrame({'units':[30,20]})

And I get

      units
 0      30
 1      20

I then add a row to total the column:

my_sum = df.sum()
df = df.append(my_sum, ignore_index=True)

Finally, I add a column to calculate percentages off of the 'units' column:

df['pct'] = df.units / df.units[:-1].sum()

ending with this:

    units   pct
 0  30     0.6
 1  20     0.4
 2  50     1.0

So far so good - but now the question: I want to change the middle number of units from 20 to, for example, 30. I can use this:

df3.iloc[1, 0] = 40

or

df3.iat[1, 0] = 40

which change the cell, but the calculated values at both the last row and second column don't change to reflect it:

    units   pct
 0  30      0.6
 1  40      0.4
 2  50      1.0

How do I force these calculated values to adjust following the change in that particular cell?

解决方法

Make a function that calculates it

def f(df):
  return df.append(df.sum(), ignore_index=True).assign(
      pct=lambda d: d.units / d.units.iat[-1])

df.iat[1, 0] = 40

f(df)

   units       pct
0     30  0.428571
1     40  0.571429
2     70  1.000000
相似信息