如何在指定列位置向Pandas DataFrame插入预初始化列或另一个DataFrame
在Pandas DataFrame的指定列之间批量插入31列(日期列)
我们有如下Pandas DataFrame:
col1 col2 col3 0 one two three 1 one two three 2 one two three 3 one two three 4 one two three
需要在col2和col3之间插入编号为1到31的31列,初始代码如下:
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'], })
实现方案
可以通过定位目标列的索引,循环插入新列来实现,具体代码如下:
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'], }) # 获取col2的索引位置,加1得到插入的起始位置(col2之后) insert_position = src.columns.get_loc('col2') + 1 # 循环插入1到31列,这里默认填充NaN,可按需修改初始值 for day_num in range(1, 32): src.insert(insert_position, str(day_num), pd.NA) # 每插入一列,后续插入位置后移一位 insert_position += 1 # 验证结果 print(src.columns)
关键说明
src.columns.get_loc('col2')会返回col2在列列表中的索引(此处为1),加1后就得到了col2之后、col3之前的插入起始点。- 使用
DataFrame.insert()方法在指定位置插入新列,列名设为日期编号的字符串形式,初始值用pd.NA(也可以替换为0、空字符串等自定义值)。 - 每次插入列后更新
insert_position,保证后续新列依次排列在之前插入列的后面,最终所有31列都会连续放在col2和col3之间。
内容的提问来源于stack exchange,提问作者Laurent B.
相关产品推荐
相关产品推荐

