[Pandas] 添加空值列

美图欣赏2022/08/16

数据准备

import pandas as pd
 
df = pd.DataFrame([['L123','A'],
                   ['L456','A'],
                   ['L437','C']
                  ],columns=['Raw Material','Level'])

df

方法1:pandas.DataFrame.reindex()

import pandas as pd
 
df = pd.DataFrame([['L123','A'],
                   ['L456','A'],
                   ['L437','C']
                  ],columns=['Raw Material','Level'])

df = df.reindex(columns = df.columns.tolist() + ["Data1","Data2",'Data3'])

df

方法2:直接创建空值列

import pandas as pd
import numpy as np
 
df = pd.DataFrame([['L123','A'],
                   ['L456','A'],
                   ['L437','C']
                  ],columns=['Raw Material','Level'])

df["Data1"] = ""
df["Data2"] = np.nan
df['Data3'] = pd.Series() 

df 

方法3:pandas.DataFrame.assign() 

import pandas as pd
import numpy as np
 
df = pd.DataFrame([['L123','A'],
                   ['L456','A'],
                   ['L437','C']
                  ],columns=['Raw Material','Level'])

df = df.assign(Data1 = np.nan, Data2 = "", Data3 = pd.Series())

df

方法4:pandas.DataFrame.insert() 

import pandas as pd
import numpy as np
 
df = pd.DataFrame([['L123','A'],
                   ['L456','A'],
                   ['L437','C']
                  ],columns=['Raw Material','Level'])

df.insert(2, "Data1", pd.Series()) 
df.insert(3, "Data2", np.nan)
df.insert(4, "Data3", "")

df


扩展补充资料

[Pandas技巧] 添加新列https://blog.csdn.net/Hudas/article/details/125349965

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值