【问题标题】:Populate new column in dataframe based on dictionary key matches values in another column and some more conditions根据字典键匹配另一列中的值和更多条件填充数据框中的新列
【发布时间】:2021-07-23 22:09:26
【问题描述】:

我有一个类似的数据框

我有一本包含 ec2 实例详细信息的字典

现在,我想添加一个新列“实例名称”并根据字典中的实例 ID 位于“ResourceId”列中的条件填充它,并进一步取决于名称字段中的内容该实例 ID 的字典,我想为每个匹配条目填充新列值

最后,我想为我的特定用例创建单独的数据框,例如仅获得 Box-Usage 结果。像这样的

box_usage = df[df['lineItem/UsageType'].str.contains('BoxUsage')]
print(box_usage.groupby('Instance Name')['lineItem/BlendedCost'].sum())

新的列值没有像我希望的那样与相应的资源 ID 相匹配。它是按顺序出现的。 我已经尝试了很多东西,包括我在上面的代码中提到的,但还没有结果。有什么帮助吗?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    在通过几个选项苦苦挣扎后,我使用了 .apply() 方法,它成功了

    df.insert(loc=17, column='Instance_Name', value='Other')
    instance_id = []
    
    def update_col(x):
        for key, val in ec2info.items():
            if x == key:
                if ('MyAgg' in val['Name']) | ('MyAgg-AutoScalingGroup' in val['Name']):
                    return 'SharkAggregator'
                if ('MyColl AS Group' in val['Name']) | ('MyCollector-AutoScalingGroup' in val['Name']):
                    return 'SharkCollector'
                if ('MyMetric AS Group' in val['Name']) | ('MyMetric-AutoScalingGroup' in val['Name']):
                    return 'Metric'
    
    df['Instance_Name'] = df.ResourceId.apply(update_col)
    df.Instance_Name.fillna(value='Other', inplace=True)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      相关资源
      最近更新 更多