Pandas Dataframe 列移位和添加

6l7fqoea  于 2023-02-07  发布在  其他
关注(0)|答案(3)|浏览(185)

我想在现有数据框中添加一个新列。新列需要从第一行的常量值开始(在下面的示例中为-17.3),然后连续为所有26000行添加0.15。新列最后应具有以下值:

  1. -17.3
  2. -17.15
  3. -17
  4. -16.85
  5. 26000 rows

有没有什么方法可以在不循环遍历所有行的情况下完成这一操作?
谢谢你,
芳郎

tag5nh1u

tag5nh1u1#

您可以按如下方式构建范围:

  1. # 26,000 numbers
  2. # step of 0.15
  3. # starting at -17.3
  4. np.arange(26000) * 0.15 - 17.3
jobtbby3

jobtbby32#

假设您的 Dataframe 名为df,您可以通过以下方式进行命名:

  1. start_value = -17.3
  2. increment_value = 0.15
  3. new_column = [start_value + increment_value * i for i in range(df.shape[0])]
  4. df['new_column'] = new_column
mm9b1k5b

mm9b1k5b3#

pandas.Series * 构造函数 * 与pandas.Series.cumsum一起使用:

  1. N, S, F = len(df), -17.3, 0.15 # <- len(df) = 26000 in your case
  2. df["approach_1"] = pd.Series([S] + [np.NaN]*(N-1)).fillna(F).cumsum()

或者按照@tdy 简单地选择numpy.arange

  1. df["approach_2"] = np.arange(S, S + N*F, F)

输出:

  1. print(df)
  2. approach_1 approach_2
  3. 0 -17.30 -17.30
  4. 1 -17.15 -17.15
  5. 2 -17.00 -17.00
  6. 3 -16.85 -16.85
  7. 4 -16.70 -16.70
  8. ... ... ...
  9. 25995 3881.95 3881.95
  10. 25996 3882.10 3882.10
  11. 25997 3882.25 3882.25
  12. 25998 3882.40 3882.40
  13. 25999 3882.55 3882.55
  14. [26000 rows x 2 columns]
展开查看全部

相关问题