首页 > 解决方案 > 如何添加具有值长度和自定义开始的新列?

问题描述

有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

我已经google了,但我找不到解决方案。

标签: pythonpandasdataframerange

解决方案


import numpy as np
df1['counter'] = np.arange(df2['counter_2'].max(), len(df1) + 1)

推荐阅读