python – 将列表中零值的多个列添加到Pandas数据框中
发布时间:2020-12-20 11:48:14 所属栏目:Python 来源:网络整理
导读:说我有一个数据框 id col1 col21 1 foo2 1 bar 列名列表 l = ['col3','col4','col5'] 如何在数值为零的情况下向数据框添加新列? id col1 col2 col3 col4 col51 1 foo 0 0 02 1 bar 0 0 0 解决方法 您可以尝试直接分配(假设您的数据框名为df): for col in l
说我有一个数据框
id col1 col2 1 1 foo 2 1 bar 列名列表 l = ['col3','col4','col5'] 如何在数值为零的情况下向数据框添加新列? id col1 col2 col3 col4 col5 1 1 foo 0 0 0 2 1 bar 0 0 0 解决方法
您可以尝试直接分配(假设您的数据框名为df):
for col in l: df[col] = 0 或者使用DataFrame的assign方法,如果l可以包含值,数组或任何pandas Series构造函数,这是一种更简洁的方法. # create a dictionary of column names and the value you want d = dict.fromkeys(l,0) df.assign(**d) 关于assign方法的Pandas文档:http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |