在数据框中创建一列,该列是一串字符,汇总其他列中的数据 [英] Create a column in a dataframe that is a string of characters summarizing data in other columns

查看:68
本文介绍了在数据框中创建一列,该列是一串字符,汇总其他列中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数据框,其中的列是一些指标的得分:

I have a dataframe like this where the columns are the scores of some metrics:

A B C D  
4 3 3 1  
2 5 2 2  
3 5 2 4  

我想使用列名作为字符串来创建一个新列,以总结每行超过设置阈值的指标.因此,如果阈值是A> 2,B> 3,C> 1,D> 3,我希望新列看起来像这样:

I want to create a new column to summarize which metrics each row scored over a set threshold in, using the column name as a string. So if the threshold was A > 2, B > 3, C > 1, D > 3, I would want the new column to look like this:

A B C D NewCol  
4 3 3 1 AC  
2 5 2 2 BC  
3 5 2 4 ABCD  

我尝试使用一系列np.where:

I tried using a series of np.where:

df[NewCol] = np.where(df['A'] > 2, 'A', '')  
df[NewCol] = np.where(df['B'] > 3, 'B', '')

但意识到,只要所有四个指标均不满足条件,结果就会被最后一个指标覆盖,就像这样:

but realized the result was overwriting with the last metric any time all four metrics didn't meet the conditions, like so:

A B C D NewCol  
4 3 3 1 C  
2 5 2 2 C  
3 5 2 4 ABCD  

我很确定有一种更简单正确的方法.

I am pretty sure there is an easier and correct way to do this.

推荐答案

您可以这样做:

import pandas as pd

data = [[4, 3, 3, 1],
        [2, 5, 2, 2],
        [3, 5, 2, 4]]

df = pd.DataFrame(data=data, columns=['A', 'B', 'C', 'D'])

th = {'A': 2, 'B': 3, 'C': 1, 'D': 3}

df['result'] = [''.join(k for k in df.columns if record[k] > th[k]) for record in df.to_dict('records')]

print(df)

输出

   A  B  C  D result
0  4  3  3  1     AC
1  2  5  2  2     BC
2  3  5  2  4   ABCD

这篇关于在数据框中创建一列,该列是一串字符,汇总其他列中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆