gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:54:40 27 4
gpt4 key购买 nike

我想在数据框中添加两列,假设我们在数据框中有 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

关于python - 我想在具有增量值的数据框中添加两列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47345132/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com