【问题标题】:Update dataframe rows trough loop通过循环更新数据框行
【发布时间】:2020-07-12 03:25:51
【问题描述】:

我有一个数据框,我想创建一些包含原始列增长的新列。

首先,我将新列附加到数据框中,用 NaN 值填充它们。

然后,对于每一行,我检查前一行是否对应于上一年,如果是,我想用变量的增长填充新列。否则我只留下 NaN 值。

这是我的代码:

for index, row in df.iterrows():
   if df.loc[index,'year'] == df.loc[index - 1, 'year'] + 1 and df.loc[index,'name'] == df.loc[index - 1, 'name']:
       df.loc[index,k:] = (df.loc[index,1:k-1]/df.loc[index-1,1:k-1]) - 1

其中 k 是我创建的第一个新“增长”列的列索引。

此代码的问题在于它在新列中留下了 NaN 值,而没有进行任何更改。我做错什么了吗?

谢谢

【问题讨论】:

  • df.merge(df.assign(year=df.year+1), on = 'year'...) 的东西。
  • 谢谢。我每年都有多个观察(公司),我不确定这会奏效。数据框最初按公司名称排序,然后按年份排序,并且在 if 条件中还有一个 and 条件,即该行的公司名称等于上一行中的公司名称。

标签: python pandas loops dataframe indexing


【解决方案1】:
df.sort_values('year', inplace = True)
growth_cols = [<your-growth-cols>]
new_cols = [x + "_growth" for x in growth_cols]
growth_df = df[growth_cols] / df[growth_cols].shift(1)
growth_df.rename(columns = dict(zip(growth_cols, new_cols)), inplace = True)
df = pd.concat([df, growth_df], axis =1)
df['gap'] = df.year.diff()
for col in new_cols:
    df[col] = df[col] * df['gap']
    df[col].replace(0, np.nan, inplace = True)
df.drop('gap', axis = 1, inplace = True)

编辑(基于更新的问题):

你需要换行

df['gap'] = df.year.diff()

到:

df['gap'] = df.groupby('name').diff()

【讨论】:

  • 非常感谢 Bishwarup。我不能只移动整个数据框并进行划分,因为所有行都与连续年份无关。此外,同一年我有多家公司(列:'name'),所以在填写新行之前,如果必须检查公司名称是否相同。数据框最初按公司名称排序,然后按年份排序,并且在循环的 if 条件中,还有一个 and 条件,即该行的公司名称等于上一行中的公司名称。我更新了问题中的代码以使其更加清晰。
  • 我已根据其他输入更新了我的答案。希望对您有所帮助。
  • 谢谢!应该管用。几个问题:我认为更新后的行应该是:df['gap'] = df.groupby('name').year.diff(),对吗?而且,我猜在运行循环之前,应该只保留 ratios['gap'] 等于 1 的值。
  • 没错,我一回到办公桌上就开始编辑。此外,在运行最后一个 for 循环之前,您可以选择保留对应于 year = 1 的行,或者将其保留为与任何其他行一样,增长将设置为 NaN。如果您发现我的代码有帮助,请考虑投票。谢谢你:)
猜你喜欢
  • 1970-01-01
  • 2021-05-08
  • 2011-09-09
  • 2021-07-12
  • 2015-06-18
  • 1970-01-01
  • 2019-06-18
  • 2011-11-03
  • 2017-10-10
相关资源
最近更新 更多