【问题标题】:Auto-generation of new columns based on existing columns基于现有列自动生成新列
【发布时间】:2020-06-30 13:07:54
【问题描述】:

我想根据 pandas 数据框中的其他列创建新列,并对其进行一些逻辑处理。对于名称为 [string] > Full Name 的每一列,我想生成两个名为 [string] > Asset Type[string] > 的新列域。还有一些列没有这个[string]>Full Name结构,这些需要保持不变。

这是我所拥有的:

data = pd.DataFrame({'recipient > Full Name': {0: 'Norway', 1: 'Sweden'},
                    'transporter > Full Name': {0: "UPS", 1: "Sweden Mail Services"},
                    'Description': {0:'Priority mail', 1: 'Fragile object - be careful'}})

这就是我想要的:

wantedData = pd.DataFrame({'recipient > Full Name': {0: 'Norway', 1: 'Sweden'},
                    'transporter > Full Name': {0: "UPS", 1: "Sweden Mail Services"},
                    'Description': {0:'Priority mail', 1: 'Fragile object - be careful'},
                    'recipient > Asset Type': {0: "Country", 1: "Country"},
                    'recipient > Domain': {0: "Transport", 1: "Transport"},
                    'transporter > Asset Type': {0: "Legal Enitity", 1: "Legal Entity"},
                    'transporter > Domain': {0: "Transport", 1: "Transport"}})

此外,所有 Domain 列的所有行的值都相同,有没有办法用我在代码中使用的示例“Transport”自动填充它?

我尝试创建一些查看第 0 列并基于第 0 列创建第 1 列和第 2 列的代码 - 并迭代所有列,但这与我想要保持不变的列混淆。

【问题讨论】:

    标签: python pandas automation transform


    【解决方案1】:
    import pandas as pd
    
    data = pd.DataFrame({'recipient > Full Name': {0: 'Norway', 1: 'Sweden'},
                    'transporter > Full Name': {0: "UPS", 1: "Sweden Mail Services"},
                    'Description': {0:'Priority mail', 1: 'Fragile object - be careful'}})
    
    # value_dict contains initial values for new columns (except those ending with Domain) 
    value_dict = {
        'recipient > Asset Type' : 'Country',
        'transporter > Asset Type' : 'Legal Entity'
    }
    
    # key_list contains combination of new columns - in this case we want to create 
    # 2 new columns (... Asset Type, ... Domain) for each column containing '>' 
    key_list = ['Asset Type', 'Domain']
    
    # iterate through list of column names containing '>' (other columns remain untouched)
    for col in [col for col in data.columns if '>' in col]:
        # and for each such column create 2 new columns with new names (could be more or less...depends on key_list)
        for i in range(len(key_list)):
            new_colname = '{} > {}'.format(col.split(' >')[0], key_list[i%len(key_list)])
            # set Transport as value if column ends with '> Domain' or value from value_dict or None if not specified
            new_value = 'Transport' if new_colname.endswith('> Domain') else value_dict[new_colname] if new_colname in value_dict else None 
            data[new_colname] = new_value
    

    输出:

    【讨论】:

      猜你喜欢
      • 2017-01-11
      • 2019-09-10
      • 1970-01-01
      • 2020-02-18
      • 1970-01-01
      • 1970-01-01
      • 2019-04-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多