在数据框中创建一列,该列是一串字符,汇总其他列中的数据
我有一个这样的数据框,其中的列是一些指标的得分:
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