【问题标题】:Create new column in python 3 (pandas) dataframe based on value in other column根据其他列中的值在 python 3 (pandas) 数据框中创建新列
【发布时间】:2020-12-05 13:50:06
【问题描述】:

我有一个 pandas 数据框,我需要根据数据框中其他列的值创建新列。这是数据框

人城市州国家

美国伊利诺伊州芝加哥

B 美国亚利桑那州凤凰城

C 美国加利福尼亚州圣地亚哥

我想根据 state 中的值创建两个新列

  1. 创建新列 df["city-north"] = df['city'] where state = "Illinois"
  2. 创建新列 df["city-south"] = df['city'] 其中 state 不等于“Illinois”

我试过了

df.loc[((df['state'] == 'Illinois')), 'city-north'] = df['city']

df.loc[((df['state'] != 'Illinois')), 'city-south'] = df['city']

但不等于条件的第二行代码不会创建“city-south”列。请帮忙

【问题讨论】:

    标签: python-3.x pandas dataframe


    【解决方案1】:

    对我来说工作得很好,如果没有创建匹配条件缺失值:

    df.loc[df['state'] == 'Illinois', 'city-north'] = df['city']
    df.loc[df['state'] != 'Illinois', 'city-south'] = df['city']
    
    print (df)
      person       city       state country city-north city-south
    0      A    Chicago    Illinois     USA    Chicago        NaN
    1      B    Phoenix     Arizona     USA        NaN    Phoenix
    2      C  San Diego  California     USA        NaN  San Diego
    

    如果不匹配的行需要空值字符串:

    df['city-north'] = np.where(df['state'] == 'Illinois', df['city'], '')
    df['city-south'] = np.where(df['state'] != 'Illinois', df['city'], '')
    
    print (df)
      person       city       state country city-north city-south
    0      A    Chicago    Illinois     USA    Chicago           
    1      B    Phoenix     Arizona     USA               Phoenix
    2      C  San Diego  California     USA             San Diego
    

    【讨论】:

      【解决方案2】:

      我认为您的代码应该可以正常工作。

      df.loc[df['state'] == 'Illinois', 'city-north'] = df['city']
      

      df.loc[df['state'] != 'Illinois', 'city-south'] = df['city']

      我什至尝试了多个条件和新输入,这些条件和新输入不在原始数据框中,并且仍然按如下方式工作:

      df.loc[(df['state'] == 'Illinois') & (df['city'] =='Chicago'), 'city-north'] = 'New Entry']

      df.loc[(df['state'] != 'Illinois') & (df['city'] =='Phoenix '), 'city-south'] = 'Another new entry'

      请注意,我的回答的第二部分是在多个条件下显示更清晰,它仍然有效。它可用于添加带有新条目的新列。

      【讨论】:

        猜你喜欢
        • 2021-08-27
        • 2021-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-16
        • 1970-01-01
        • 2020-04-12
        • 1970-01-01
        相关资源
        最近更新 更多