Warm tip: This article is reproduced from serverfault.com, please click

python-将数据框列添加到特定位置

(python - Adding a dataframe column to a specific position)

发布于 2020-11-27 23:14:36

我正在从数据框中提取一列,因此我可以处理其余数据框列中的功能并将其存储在变量中。我想做的是将该列返回到它的位置,例如:

原始数据框:

samples = {'col1': [1, 3, 5, 6, 7, 9, 11, 12],
        'col2': [1, 0, 1, 1, 0, 1, 0, 1],
        'col3': [10, 15, 16, 17, 19, 12, 10, 31],
        }

df = pd.DataFrame(samples, columns = ['col1', 'col2', 'col3'])

将第一列存储在df_col1中

df_col1 = df.iloc[:, 0:0]
df = df.iloc[:, 1:]

我想做的是将内部的列添加df_col1回它在数据框中的原始位置df

Questioner
rckjns
Viewed
0
piterbarg 2020-11-28 07:26:29

假设你知道位置(将其存储在某个位置),或者很乐意直接指定位置,假设你希望在pos 0中使用该位置(在代码中将其删除之后)

df.insert(0,df_col1.columns[0], df_col1)