【问题标题】:How to add new column with the length of the values and the custom start?如何添加具有值长度和自定义开始的新列?
【发布时间】:2020-01-30 12:08:05
【问题描述】:

有 2 个数据框

df1 和 df2

df1 =

A   B
111 222
222 5555

df2 =

C   counter_2
333 100
777 25

我需要在df1中添加一个“计数器”列,它应该就像索引一样,返回列元素的位置。

像这样:

df1['counter'] = range(len(df1))

A   B   counter
111 222       1
222 555       2

但我需要更改起点,它应该是 df2 "counter" 列中的最大数字。

df2['counter_2'].max() # 100

所以我想要的输出是这样的:

A   B   counter
111 222       101
222 555       102

我已经用谷歌搜索了,但我找不到解决方案。

【问题讨论】:

    标签: python pandas dataframe range


    【解决方案1】:

    当我们创建数据框时,它有一个默认索引,您没有在上面显示。如果您已将另一列设置为索引,那么您将不得不重置它,然后添加包含 counter2 和索引最大值总和的新列,如下所示:

     max_value = df2['counter_2'].max()     
     df1 = df1.reset_index()
     df1['counter'] = df1.index+max_value
     print(df1.head())
    

    还为列和数据框使用有意义的名称。 谢谢。

    【讨论】:

      【解决方案2】:
      # First, compute the starting point
      start_point = df2['counter_2'].max() + 1
      
      # Now, assign a range of numbers to the 'counter' column of df1
      df1['counter'] = list(range(start_point, start_point + len(df1)))
      

      【讨论】:

        【解决方案3】:
        import numpy as np
        df1['counter'] = np.arange(df2['counter_2'].max(), len(df1) + 1)
        

        【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多