Skip to main content
 首页 » 编程设计

python之我想在具有增量值的数据框中添加两列

2025年01月19日11三少

我想在数据框中添加两列,假设我们在数据框中有 50 行,那么我的第 1 列值应该是 1 到 50,第 2 列值应该是 51 到 100。

def insertId(new_df, str): 
    df.insertId(0, str, range(1, 1 + len(df))) 
    return df 

为了满足我的要求,上述功能需要修正,但由于我是 Python 初学者,无法修正。

请您参考如下方法:

创建第一个 numpy 数组 并将其传递给 DataFrame 构造函数:

a = np.arange(1, 101).reshape(2,-1).T 
df1 = pd.DataFrame(a, columns=['a','b']) 
 
print(df1.head()) 
 
   a   b 
0  1  51 
1  2  52 
2  3  53 
3  4  54 
4  5  55 

最后将其添加到原始DataFrame:

df = df.join(df1) 

用你的函数解决 insert - 可以指定列 pos 的位置,然后是列名 col 和最后一个开始编号 start:

#some Dataframe 
a = np.arange(1, 101).reshape(2,-1).T 
df = pd.DataFrame(a, columns=['a','b']) 
print (df.head()) 
   a   b 
0  1  51 
1  2  52 
2  3  53 
3  4  54 
4  5  55 
 
def insertId(new_df, pos, col, start): 
    new_df.insert(pos, col, range(start, len(new_df) + start)) 
    return new_df 
 
#insert new column called s to DataFrame df in position 0 and values starts in 50 
df = insertId(df, 0, 's', 50) 
df = insertId(df, 2, 'new', 14) 
print (df.head()) 
 
    s  a  new   b 
0  50  1   14  51 
1  51  2   15  52 
2  52  3   16  53 
3  53  4   17  54 
4  54  5   18  55