【问题标题】:Generate multiple columns based on conditions from other columns根据其他列的条件生成多列
【发布时间】:2020-05-29 06:47:09
【问题描述】:

我已经搜索了很多解决方案,但几乎所有问题都与创建单个列有关。 所以,这是我的问题。

给定一个示例 DataFrame:

df = pd.DataFrame({
    "blue": [5, 5, 4], 
    "red": [1, 7, 5],
    "yellow": [3, 9, 0],
    "orange": [9, 7, 3],
    "config": ["north", "south", "north"]
})
   blue config  orange  red  yellow
0     5  north       9    1       3
1     5  south       7    7       9
2     4  north       3    5       0

我想要实现的是基于多个条件(具体的映射)创建额外的列。这是我尝试过的一个示例:

def gen_col(row):

    if row["config"] == "north":
        new_blue = row["blue"]
        new_red = row["red"]
        new_yellow = row["yellow"]
        new_orange = row["orange"]
        return new_blue, new_red, new_yellow, new_orange
    elif row["config"] == "south":
        new_blue = row["orange"]
        new_red = row["yellow"]
        new_yellow = row["red"]
        new_orange = row["blue"]
        return new_blue, new_red, new_yellow, new_orange

df["new_blue", "new_red", "new_yellow", "new_orange"] = df.apply(gen_col, axis=1)

但是,这会返回以下内容:

   blue config  orange  red  yellow (new_blue, new_red, new_yellow, new_orange)
0     5  north       9    1       3             (5, 1, 3, 9)
1     5  south       7    7       9             (7, 9, 7, 5)
2     4  north       3    5       0             (4, 5, 0, 3)                         

关于如何创建单独新列的任何想法?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    DataFrame.apply 中使用result_type='expand' 参数,并为分配的列添加嵌套列表:

    df[["new_blue", "new_red", "new_yellow", "new_orange"]] = df.apply(gen_col, axis=1, result_type='expand')
    print (df)
       blue  red  yellow  orange config  new_blue  new_red  new_yellow  new_orange
    0     5    1       3       9  north         5        1           3           9
    1     5    7       9       7  south         7        9           7           5
    2     4    5       0       3  north         4        5           0           3
    

    【讨论】:

    • 感谢闪电般的快速回复!并注意自己,仔细查看文档:)
    • @jezrael 您似乎对熊猫非常了解。您能否帮助我提供您对此的看法? stackoverflow.com/questions/62069465/… 谢谢。
    猜你喜欢
    • 2019-12-17
    • 2016-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    相关资源
    最近更新 更多