【问题标题】:Create a Pandas Column that Starts with x and Incremented by y创建一个以 x 开头并以 y 为增量的 Pandas 列
【发布时间】:2021-01-19 01:20:20
【问题描述】:

我想在我的 pandas DataFrame (New_Column) 中创建另一列,其起始值为 x,然后后续行递增 y(或取上一行并添加 y)。

例如:起始值为2000,递增7

Index  Date        New_Column
0      10-02-2020  2000
1      10-01-2020  2007
2      09-30-2020  2014
3      09-29-2020  2021

我添加了日期列,因为这是我的 DataFrame 中唯一的唯一列,不知道这是否重要。我在谷歌的 Colaboratory 工作。我尝试使用 for 循环无济于事,以及其他 Stack 用户索引建议。

【问题讨论】:

  • 你能添加你尝试写的代码吗?
  • 仅供参考:彻底回答问题非常耗时。如果您的问题已解决,请通过接受最适合您的需求的解决方案表示感谢。 接受检查位于答案左上角的向上/向下箭头下方。如果出现更好的解决方案,则可以接受新的解决方案。如果您的声誉超过 15,您还可以使用向上或向下箭头对答案的质量/有用性进行投票。 如果解决方案无法回答问题,请发表评论。 What should I do when someone answers my question?。谢谢。

标签: python-3.x pandas dataframe google-colaboratory increment


【解决方案1】:

你可以这样做:

df['new'] = np.arange(x, x+len(df)*y, y)

【讨论】:

    【解决方案2】:

    你可以使用 numpy 的 arange:

    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({'Date': pd.date_range('2020-09-29', periods=4, freq='D')[::-1]})
    start_val = 2000
    increm = 7
    df['New column'] = np.arange(start=start_val, stop=start_val+len(df)*increm, step=increm)
    

    结果数据框:

            Date  New column
    0 2020-10-02        2000
    1 2020-10-01        2007
    2 2020-09-30        2014
    3 2020-09-29        2021
    

    【讨论】:

      【解决方案3】:

      您可以在将新列数据添加到数据框之前创建它。您可以在下面的代码中看到一个示例:

      import pandas as pd
      df = pd.DataFrame({'Date': [ "10-02-2020","10-01-2020","09-30-2020","09-29-2020"]})
      newData = []
      starting = 2000
      incr = 7
      numRows = len(df.index)
      for i in range(0,numRows):
          newData.append(starting)
          starting+=incr
      df["New_Column"] = newData
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多