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
234 views
in Technique[技术] by (71.8m points)

pandas - Compare values under multiple conditions of one column in Python

I have the following data:

data = {
    "index": [1, 2, 3, 4, 5],
    "name": ["A", "A", "B", "B", "B"],
    "type": ['s1', 's2', 's1', 's2', 's3'],
    'value': [20, 10, 18, 32, 25]
}
df = pd.DataFrame(data)

I need to check if the value under same name follow constraint (say there only three type and not all exist under same name): s1 < s2 < s3, which means, under same name, if the value of s1 is smaller than s2 or s3, then return True, if s2 is smaller than s3, then return True. Otherwise, return False or NaN. Here is the output I expected:

    index   name    type    value   result
0     1      A       s1      20      False
1     2      A       s2      10        
2     3      B       s1      18      True
3     4      B       s2      32      False
4     5      B       s3      25        

How can I do it in Python? Thanks for your help.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Try:

#Use pd.Categorical to ensure sorting if column is not lexicographical ordered.
df['type'] = pd.Categorical(df['type'], ordered=True, categories=['s1','s2','s3'])

df['result'] = df.sort_values('type').groupby('name')['value'].diff(-1)

df['result'] = df['result'].lt(0).mask(df['result'].isna(),'')

df

Output:

   index name type  value result
0      1    A   s1     20  False
1      2    A   s2     10       
2      3    B   s1     18   True
3      4    B   s2     32  False
4      5    B   s3     25       

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

1.4m articles

1.4m replys

5 comments

56.9k users

...