向pandas DataFrame对象添加空列的最简单方法是什么?我碰到的最好的是
df['foo'] = df.apply(lambda _: '', axis=1)
有没有更合理的方法?
向pandas DataFrame对象添加空列的最简单方法是什么?我碰到的最好的是
df['foo'] = df.apply(lambda _: '', axis=1)
有没有更合理的方法?
当前回答
可以用df。插入(index_to_insert_at, column_header, init_value)在特定索引处插入新列。
cost_tbl.insert(1, "col_name", "")
上面的语句将在第一列之后插入一个空列。
其他回答
如果您想从列表中添加列名
df=pd.DataFrame()
a=['col1','col2','col3','col4']
for i in a:
df[i]=np.nan
下面的代码解决了“如何向现有数据框架中添加n个空列”的问题。为了将类似问题的解决方案保存在一个地方,我在这里添加了它。
方法1(创建64个附加列,列名从1到64)
m = list(range(1,65,1))
dd=pd.DataFrame(columns=m)
df.join(dd).replace(np.nan,'') #df is the dataframe that already exists
方法2(创建64个附加列,列名从1到64)
df.reindex(df.columns.tolist() + list(range(1,65,1)), axis=1).replace(np.nan,'')
可以用df。插入(index_to_insert_at, column_header, init_value)在特定索引处插入新列。
cost_tbl.insert(1, "col_name", "")
上面的语句将在第一列之后插入一个空列。
一个更简单的解决方案是:
df = df.reindex(columns = header_list)
其中“header_list”是你想要显示的标题列表。
列表中包含的任何标题,如果在数据帧中没有找到,将在下面添加空白单元格。
因此,如果
header_list = ['a','b','c', 'd']
然后将c和d添加为带空白单元格的列
你可以这样做
df['column'] = None #This works. This will create a new column with None type
df.column = None #This will work only when the column is already present in the dataframe