【问题标题】:Add multiple columns with zero values from a list to a Pandas data frame将列表中具有零值的多个列添加到 Pandas 数据框中
【发布时间】:2016-04-12 14:24:30
【问题描述】:

假设我有一个数据框

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

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以尝试直接分配(假设您的数据框名为 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

    【讨论】:

    • 您的d 可以更简单地写成dict.fromkeys(l, 0)。 (但警告:由于我们使用的是字典,因此不能保证顺序是 l 的顺序。)
    • 谢谢!添加了更改。
    • 您将如何强制该列的 dtype 是 int32 而不是 float64?我试过df[col] = int(0),还用astype(int) 转换了整个列,但没有用
    • 这很奇怪,做df[col] = df[col].astype({col: "int32"})应该就够了@它会有助于发布一个可重现的例子。
    • 用字典赋值的例子解释stackoverflow.com/questions/42101382/…
    猜你喜欢
    • 2017-05-02
    • 1970-01-01
    • 2019-10-20
    • 2020-10-10
    • 2018-02-26
    • 2020-07-14
    • 2021-11-09
    • 1970-01-01
    • 2016-08-17
    相关资源
    最近更新 更多