Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

python - Create a column in a dataframe that is a string of characters summarizing data in other columns

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  

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  

I tried using a series of np.where:

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

etc.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could do:

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)

Output

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...