Compare values under multiple conditions of one column in Python

2024/7/4 15:15:03

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.

Answer

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       
https://en.xdnf.cn/q/120175.html

Related Q&A

Python: Tkinter :Dynamically Create Label

I am trying to create Label Dynamically , I am getting invalid Syntax. Can you please help me what i am missing or any alternativecrsr = cnxn.execute(query)row_num=2column_num=0Variable_Number=1for row…

TypeError: str object is not callable when trying to click datepicker

The relevant HTML<div id="datepickerbox" class="ym-gbox-left"><div class="datepick_label"><div id="datepicker" class="hasDatepicker">…

Stanford parser with NLTK produces empty output

I am trying to use the Stanford parser in a small application written in Python with the NLTK interface. I tried the code given below.Everything seems to work right, no errors, Java is launched but I s…

How do you return a list of the matched item in string with regex? [duplicate]

This question already has answers here:Regular expression to match a dot [duplicate](8 answers)Closed 3 years ago.I made this simple functions that searches for emails in the source code of a page , th…

Indentation Error [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable…

open csv file in python to customize dictionary [duplicate]

This question already has answers here:Creating a dictionary from a CSV file(4 answers)Closed 9 years ago.I would like to know to load this csv file:Epitope,ID,Frequency,AssayAVNIVGYSNAQGVDY,123431,27.…

How does UserPassesTestMixin in django work?

views.pyclass ProfileEdit(UserPassesTestMixin, UpdateView):model = Userform_class = ProfileFormtemplate_name="profile/profile_new.html"def test_func(self):x = self.request.user.idprint (x)y =…

How to extract URL from HTML anchor element using Python3? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 9 years ago.Improve…

Why does using open(filename) fail with filename is not defined?

I want to open a text file containing a column of words and create a list or, alternatively, a string containing these words. Why do I get this error: >>> with open(some_file.txt, r) as some_f…

Read Excel file which has one of the column as Hyperlink through python

I have to read an Excel file Using python. By the time I use xl = pd.ExcelFile("abc.xlsx")The column values which had hyperlink assigned to it becomes a simple number without any hyperlink.Is…