如何在指定的列位置插入前定位数据框或几列?

问题描述 投票:0回答:4

支持我们有以下数据框。

col1 col2 col3 0 one two three 1 one two three 2 one two three 3 one two three 4 one two three
我们试图将31列引入此数据框架,每列代表当月的一天。
llet说我们想精确地将其介绍在列之间。

我们如何实现?

要简单,引入的列可以从1到31。

启动源代码

col2

其他可能的解决方案:

col3 输出:

import pandas as pd

src = pd.DataFrame({'col1': ['one', 'one', 'one', 'one','one'],    
                    'col2': ['two', 'two', 'two', 'two','two'],    
                    'col3': ['three', 'three', 'three', 'three','three'],
                    })
python pandas dataframe numpy join
4个回答
1
投票

您可以使用

pd.concat([src.iloc[:, :2].assign(
    **{str(col): 0 for col in range(1, 32)}), src['col3']], axis=1)

和重新排序列,如下所示:

  col1 col2  1  2  3  4  5  6  7  8  ...  23  24  25  26  27  28  29  30  31  \
0  one  two  0  0  0  0  0  0  0  0  ...   0   0   0   0   0   0   0   0   0   
1  one  two  0  0  0  0  0  0  0  0  ...   0   0   0   0   0   0   0   0   0   
2  one  two  0  0  0  0  0  0  0  0  ...   0   0   0   0   0   0   0   0   0   
3  one  two  0  0  0  0  0  0  0  0  ...   0   0   0   0   0   0   0   0   0   
4  one  two  0  0  0  0  0  0  0  0  ...   0   0   0   0   0   0   0   0   0   

    col3  
0  three  
1  three  
2  three  
3  three  
4  three  

[5 rows x 34 columns]

1
投票

pd.concat


I将为原始数据框架分配值,并使用列选择重新排序列。
iloc
或全新的副本,请使用
import numpy as np # Create dataframe with 31 column and 5 rows tmp = pd.DataFrame(np.zeros((5, 31)), columns=range(1, 32)) # Concat two dataframes and reorder columns as you like df = pd.concat([src.iloc[:,:2], tmp, src.iloc[:, 2:]], axis=1)

  col1 col2    1    2    3    4    5    6    7    8  ...   23   24   25   26  \
0  one  two  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  ...  0.0  0.0  0.0  0.0   
1  one  two  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  ...  0.0  0.0  0.0  0.0   
2  one  two  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  ...  0.0  0.0  0.0  0.0   
3  one  two  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  ...  0.0  0.0  0.0  0.0   
4  one  two  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  ...  0.0  0.0  0.0  0.0   

    27   28   29   30   31   col3  
0  0.0  0.0  0.0  0.0  0.0  three  
1  0.0  0.0  0.0  0.0  0.0  three  
2  0.0  0.0  0.0  0.0  0.0  three  
3  0.0  0.0  0.0  0.0  0.0  three  
4  0.0  0.0  0.0  0.0  0.0  three  

[5 rows x 34 columns]


1
投票

如果您的目的是添加和初始化新列,请使用
src[list(range(1, 32))] = 0 src = src[[*src.columns[:2], *range(1, 32), src.columns[2]]]

assign

输出:

cols = list(map(str, range(1, 32))) new_df = ( src .assign(**dict.fromkeys(cols, 0)) .reindex(columns=[*src.columns[:2], *cols, *src.columns[2:]]) ) res


1
投票
reindex

result

cols = list(src)
cols[2:2] = range(1,31+1)

df = src.reindex(columns=cols, fill_value=0)


最新问题
© www.soinside.com 2019 - 2025. All rights reserved.