Compare consecutive dataframe rows based on columns in Python












0















I have a dataframe. It has data about suppliers. If the name of the supplier and group are same, number of units should ideally be the same. However, sometimes that is not the case. I am writing code that imports data from SQL into Python then compares for these numbers.



This is for Python 3. Importing the data into Python was easy. I am a Python rookie. To make things easier for myself, I created individual dataframes for each supplier to compare numbers instead of looking at the whole dataframe at once.



supp = data['Supplier']
supplier =
for s in supp:
if s not in Supplier:
supplier.append(s)

su = "Authentic Brands Group LLC"
deal = defaultdict(list)
blist =
glist =
columns = ['Supplier','ID','Units','Grp']
df3 = pd.DataFrame(columns=columns)
def add_row(df3, row):
df3.loc[-1] = row
df3.index = df3.index + 1
return df3.sort_index()

for row in data.itertuples():
for x in supplier:
s1 = row.Supplier
if s1 == su:
if row.Supplier_Group not in glist:
glist.append(row.Supplier_Group)
for g in range(len(glist)):
if glist[g]==row.Supplier_Group:
supp = x
blist=
blist.append(row.ID)
blist.append(row.Units)
blist.append(glist[g])
add_row(df3,[b1,row.ID,row.Units,glist[g]])
break
break
break
for i in range(1,len(df3)):
if df3.Supplier.loc[i] == df3.Supplier.loc[i-1] and df3.Grp.loc[i] == df3.Grp.loc[i-1]:
print(df3.Supplier,df3.Grp)


This gives me a small subset that looks like this:



enter image description here



Now I want to look at the supplier name and Grp, if they are same as others in dataframe, Units should be same. In this case, row 2 is incorrect. Units should be 100. I want to add another column to this dataframe that says 'False' if the number of Units is correct. This is the tricky part for me. I can iterrate over the rows, but I'm unsure how to compare them and add column.



I'm stuck at this point.
Any help is highly appreciated. Thank you.










share|improve this question























  • What is your logic for determining which value of units is correct? Is the first record of that group always correct? Is it the most popular number ('mode')?

    – Scott Boston
    Jan 21 at 13:40











  • The number of units should be the same within the group. In this case, for Group A, the new column should say 'False' for all three rows.

    – frisbeee
    Jan 22 at 1:55
















0















I have a dataframe. It has data about suppliers. If the name of the supplier and group are same, number of units should ideally be the same. However, sometimes that is not the case. I am writing code that imports data from SQL into Python then compares for these numbers.



This is for Python 3. Importing the data into Python was easy. I am a Python rookie. To make things easier for myself, I created individual dataframes for each supplier to compare numbers instead of looking at the whole dataframe at once.



supp = data['Supplier']
supplier =
for s in supp:
if s not in Supplier:
supplier.append(s)

su = "Authentic Brands Group LLC"
deal = defaultdict(list)
blist =
glist =
columns = ['Supplier','ID','Units','Grp']
df3 = pd.DataFrame(columns=columns)
def add_row(df3, row):
df3.loc[-1] = row
df3.index = df3.index + 1
return df3.sort_index()

for row in data.itertuples():
for x in supplier:
s1 = row.Supplier
if s1 == su:
if row.Supplier_Group not in glist:
glist.append(row.Supplier_Group)
for g in range(len(glist)):
if glist[g]==row.Supplier_Group:
supp = x
blist=
blist.append(row.ID)
blist.append(row.Units)
blist.append(glist[g])
add_row(df3,[b1,row.ID,row.Units,glist[g]])
break
break
break
for i in range(1,len(df3)):
if df3.Supplier.loc[i] == df3.Supplier.loc[i-1] and df3.Grp.loc[i] == df3.Grp.loc[i-1]:
print(df3.Supplier,df3.Grp)


This gives me a small subset that looks like this:



enter image description here



Now I want to look at the supplier name and Grp, if they are same as others in dataframe, Units should be same. In this case, row 2 is incorrect. Units should be 100. I want to add another column to this dataframe that says 'False' if the number of Units is correct. This is the tricky part for me. I can iterrate over the rows, but I'm unsure how to compare them and add column.



I'm stuck at this point.
Any help is highly appreciated. Thank you.










share|improve this question























  • What is your logic for determining which value of units is correct? Is the first record of that group always correct? Is it the most popular number ('mode')?

    – Scott Boston
    Jan 21 at 13:40











  • The number of units should be the same within the group. In this case, for Group A, the new column should say 'False' for all three rows.

    – frisbeee
    Jan 22 at 1:55














0












0








0








I have a dataframe. It has data about suppliers. If the name of the supplier and group are same, number of units should ideally be the same. However, sometimes that is not the case. I am writing code that imports data from SQL into Python then compares for these numbers.



This is for Python 3. Importing the data into Python was easy. I am a Python rookie. To make things easier for myself, I created individual dataframes for each supplier to compare numbers instead of looking at the whole dataframe at once.



supp = data['Supplier']
supplier =
for s in supp:
if s not in Supplier:
supplier.append(s)

su = "Authentic Brands Group LLC"
deal = defaultdict(list)
blist =
glist =
columns = ['Supplier','ID','Units','Grp']
df3 = pd.DataFrame(columns=columns)
def add_row(df3, row):
df3.loc[-1] = row
df3.index = df3.index + 1
return df3.sort_index()

for row in data.itertuples():
for x in supplier:
s1 = row.Supplier
if s1 == su:
if row.Supplier_Group not in glist:
glist.append(row.Supplier_Group)
for g in range(len(glist)):
if glist[g]==row.Supplier_Group:
supp = x
blist=
blist.append(row.ID)
blist.append(row.Units)
blist.append(glist[g])
add_row(df3,[b1,row.ID,row.Units,glist[g]])
break
break
break
for i in range(1,len(df3)):
if df3.Supplier.loc[i] == df3.Supplier.loc[i-1] and df3.Grp.loc[i] == df3.Grp.loc[i-1]:
print(df3.Supplier,df3.Grp)


This gives me a small subset that looks like this:



enter image description here



Now I want to look at the supplier name and Grp, if they are same as others in dataframe, Units should be same. In this case, row 2 is incorrect. Units should be 100. I want to add another column to this dataframe that says 'False' if the number of Units is correct. This is the tricky part for me. I can iterrate over the rows, but I'm unsure how to compare them and add column.



I'm stuck at this point.
Any help is highly appreciated. Thank you.










share|improve this question














I have a dataframe. It has data about suppliers. If the name of the supplier and group are same, number of units should ideally be the same. However, sometimes that is not the case. I am writing code that imports data from SQL into Python then compares for these numbers.



This is for Python 3. Importing the data into Python was easy. I am a Python rookie. To make things easier for myself, I created individual dataframes for each supplier to compare numbers instead of looking at the whole dataframe at once.



supp = data['Supplier']
supplier =
for s in supp:
if s not in Supplier:
supplier.append(s)

su = "Authentic Brands Group LLC"
deal = defaultdict(list)
blist =
glist =
columns = ['Supplier','ID','Units','Grp']
df3 = pd.DataFrame(columns=columns)
def add_row(df3, row):
df3.loc[-1] = row
df3.index = df3.index + 1
return df3.sort_index()

for row in data.itertuples():
for x in supplier:
s1 = row.Supplier
if s1 == su:
if row.Supplier_Group not in glist:
glist.append(row.Supplier_Group)
for g in range(len(glist)):
if glist[g]==row.Supplier_Group:
supp = x
blist=
blist.append(row.ID)
blist.append(row.Units)
blist.append(glist[g])
add_row(df3,[b1,row.ID,row.Units,glist[g]])
break
break
break
for i in range(1,len(df3)):
if df3.Supplier.loc[i] == df3.Supplier.loc[i-1] and df3.Grp.loc[i] == df3.Grp.loc[i-1]:
print(df3.Supplier,df3.Grp)


This gives me a small subset that looks like this:



enter image description here



Now I want to look at the supplier name and Grp, if they are same as others in dataframe, Units should be same. In this case, row 2 is incorrect. Units should be 100. I want to add another column to this dataframe that says 'False' if the number of Units is correct. This is the tricky part for me. I can iterrate over the rows, but I'm unsure how to compare them and add column.



I'm stuck at this point.
Any help is highly appreciated. Thank you.







python dataframe






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 18 at 23:58









frisbeeefrisbeee

256




256













  • What is your logic for determining which value of units is correct? Is the first record of that group always correct? Is it the most popular number ('mode')?

    – Scott Boston
    Jan 21 at 13:40











  • The number of units should be the same within the group. In this case, for Group A, the new column should say 'False' for all three rows.

    – frisbeee
    Jan 22 at 1:55



















  • What is your logic for determining which value of units is correct? Is the first record of that group always correct? Is it the most popular number ('mode')?

    – Scott Boston
    Jan 21 at 13:40











  • The number of units should be the same within the group. In this case, for Group A, the new column should say 'False' for all three rows.

    – frisbeee
    Jan 22 at 1:55

















What is your logic for determining which value of units is correct? Is the first record of that group always correct? Is it the most popular number ('mode')?

– Scott Boston
Jan 21 at 13:40





What is your logic for determining which value of units is correct? Is the first record of that group always correct? Is it the most popular number ('mode')?

– Scott Boston
Jan 21 at 13:40













The number of units should be the same within the group. In this case, for Group A, the new column should say 'False' for all three rows.

– frisbeee
Jan 22 at 1:55





The number of units should be the same within the group. In this case, for Group A, the new column should say 'False' for all three rows.

– frisbeee
Jan 22 at 1:55












1 Answer
1






active

oldest

votes


















0














If you have all of your data in a single dataframe, df, you can do the following:



grp_by_cols = ['Supplier', 'ID', 'Grp']
all_cols = grp_by_cols + ['Unit']
res_df = df.assign(first_unit=lambda df: df.loc[:, all_cols]
.groupby(grp_by_cols)
.transform('first'))
.assign(incorrect=lambda df: df['Unit'] == df['first_unit'])
.assign(incorrect=lambda df: df.loc[:, grp_by_cols + ['incorrect']])
.groupby(grp_by_cols)
.transform(np.any))


The first call to assign adds a single new column (called 'first_unit') that is the first value of "Unit" for each group of Supplier/ID/Grp (see grp_by_cols).



The second call to assign adds a column called 'incorrect' that is True when 'Unit' doesn't equal 'first_unit'. The third and final assign call overwrites that column to be True if any rows in that group are True. You can remove that if that's not what you want.



Then, if you want to look at the results for a single supplier, you can do something like:



res_df.query('Supplier = "Authentic Brands Group"')





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54262889%2fcompare-consecutive-dataframe-rows-based-on-columns-in-python%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    If you have all of your data in a single dataframe, df, you can do the following:



    grp_by_cols = ['Supplier', 'ID', 'Grp']
    all_cols = grp_by_cols + ['Unit']
    res_df = df.assign(first_unit=lambda df: df.loc[:, all_cols]
    .groupby(grp_by_cols)
    .transform('first'))
    .assign(incorrect=lambda df: df['Unit'] == df['first_unit'])
    .assign(incorrect=lambda df: df.loc[:, grp_by_cols + ['incorrect']])
    .groupby(grp_by_cols)
    .transform(np.any))


    The first call to assign adds a single new column (called 'first_unit') that is the first value of "Unit" for each group of Supplier/ID/Grp (see grp_by_cols).



    The second call to assign adds a column called 'incorrect' that is True when 'Unit' doesn't equal 'first_unit'. The third and final assign call overwrites that column to be True if any rows in that group are True. You can remove that if that's not what you want.



    Then, if you want to look at the results for a single supplier, you can do something like:



    res_df.query('Supplier = "Authentic Brands Group"')





    share|improve this answer




























      0














      If you have all of your data in a single dataframe, df, you can do the following:



      grp_by_cols = ['Supplier', 'ID', 'Grp']
      all_cols = grp_by_cols + ['Unit']
      res_df = df.assign(first_unit=lambda df: df.loc[:, all_cols]
      .groupby(grp_by_cols)
      .transform('first'))
      .assign(incorrect=lambda df: df['Unit'] == df['first_unit'])
      .assign(incorrect=lambda df: df.loc[:, grp_by_cols + ['incorrect']])
      .groupby(grp_by_cols)
      .transform(np.any))


      The first call to assign adds a single new column (called 'first_unit') that is the first value of "Unit" for each group of Supplier/ID/Grp (see grp_by_cols).



      The second call to assign adds a column called 'incorrect' that is True when 'Unit' doesn't equal 'first_unit'. The third and final assign call overwrites that column to be True if any rows in that group are True. You can remove that if that's not what you want.



      Then, if you want to look at the results for a single supplier, you can do something like:



      res_df.query('Supplier = "Authentic Brands Group"')





      share|improve this answer


























        0












        0








        0







        If you have all of your data in a single dataframe, df, you can do the following:



        grp_by_cols = ['Supplier', 'ID', 'Grp']
        all_cols = grp_by_cols + ['Unit']
        res_df = df.assign(first_unit=lambda df: df.loc[:, all_cols]
        .groupby(grp_by_cols)
        .transform('first'))
        .assign(incorrect=lambda df: df['Unit'] == df['first_unit'])
        .assign(incorrect=lambda df: df.loc[:, grp_by_cols + ['incorrect']])
        .groupby(grp_by_cols)
        .transform(np.any))


        The first call to assign adds a single new column (called 'first_unit') that is the first value of "Unit" for each group of Supplier/ID/Grp (see grp_by_cols).



        The second call to assign adds a column called 'incorrect' that is True when 'Unit' doesn't equal 'first_unit'. The third and final assign call overwrites that column to be True if any rows in that group are True. You can remove that if that's not what you want.



        Then, if you want to look at the results for a single supplier, you can do something like:



        res_df.query('Supplier = "Authentic Brands Group"')





        share|improve this answer













        If you have all of your data in a single dataframe, df, you can do the following:



        grp_by_cols = ['Supplier', 'ID', 'Grp']
        all_cols = grp_by_cols + ['Unit']
        res_df = df.assign(first_unit=lambda df: df.loc[:, all_cols]
        .groupby(grp_by_cols)
        .transform('first'))
        .assign(incorrect=lambda df: df['Unit'] == df['first_unit'])
        .assign(incorrect=lambda df: df.loc[:, grp_by_cols + ['incorrect']])
        .groupby(grp_by_cols)
        .transform(np.any))


        The first call to assign adds a single new column (called 'first_unit') that is the first value of "Unit" for each group of Supplier/ID/Grp (see grp_by_cols).



        The second call to assign adds a column called 'incorrect' that is True when 'Unit' doesn't equal 'first_unit'. The third and final assign call overwrites that column to be True if any rows in that group are True. You can remove that if that's not what you want.



        Then, if you want to look at the results for a single supplier, you can do something like:



        res_df.query('Supplier = "Authentic Brands Group"')






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 19 at 0:20









        PMendePMende

        1,536512




        1,536512






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54262889%2fcompare-consecutive-dataframe-rows-based-on-columns-in-python%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Homophylophilia

            Updating UILabel text programmatically using a function

            Cloud Functions - OpenCV Videocapture Read method fails for larger files from cloud storage