OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Python code to assign values in a column depending on another column

  • Thread starter Thread starter Albert Ginard
  • Start date Start date
A

Albert Ginard

Guest
I am trying to automate sth but struggling with it. It is actually my first code in Python and what I would like to order this data frame by Hotel Id (which is already done) and then create a column that says:

  • Look into the column "Hotel Id" and if the ID in row below is equal to the ID in current row, the write "Old", otherwise "New".

In this image we can see how the code gave the value "Old" in row whose ID=23

This is the code I am using and it is asigning values in the incorrect rows(see picture).:

def asignar_old_new(df):

Code:
df['Old/New'] = 'New'
for i in range(1,len(df) - 1):
    if df['Hotel Id'].iloc[i] == df['Hotel Id'].iloc[i-1]:
        df.loc[i, 'Old/New'] = 'Old'
return df
<p>I am trying to automate sth but struggling with it. It is actually my first code in Python and what I would like to order this data frame by Hotel Id (which is already done) and then create a column that says:</p>
<ul>
<li>Look into the column "Hotel Id" and if the ID in row below is equal to the ID in current row, the write "Old", otherwise "New".</li>
</ul>
<p><a href="https://i.sstatic.net/51xcJDpH.png" rel="nofollow noreferrer">In this image we can see how the code gave the value "Old" in row whose ID=23</a></p>
<p>This is the code I am using and it is asigning values in the incorrect rows(see picture).:</p>
<p>def asignar_old_new(df):</p>
<pre><code>df['Old/New'] = 'New'
for i in range(1,len(df) - 1):
if df['Hotel Id'].iloc == df['Hotel Id'].iloc[i-1]:
df.loc[i, 'Old/New'] = 'Old'
return df
</code></pre>
 

Latest posts

Top