Adjust every other row of a data frame

2024/11/15 21:57:55

I would like to change every second row of my data frame.

I have a df like this:

 Node  |  Feature | Indicator | Value | Class | Direction
--------------------------------------------------------
1     |  WPS     |     <=    | 0.27  | 4     | 1 -> 2  
--------------------------------------------------------
2     |  ABC     |     <=    | 0.40  | 5     | 1 -> 3
--------------------------------------------------------
3     |  CXC     |     <=    | 0.45  | 2     | 2 -> 4
--------------------------------------------------------
4     |  DFT     |     <=    | 0.56  | 1     | 2 -> 5
--------------------------------------------------------
5     |  KPL     |     <=    | 0.30  | 3     | 3 -> 5
--------------------------------------------------------
6     |  ERT     |     <=    | 0.55  | 5     | 3 -> 1

I would like the following:

 Node  |  Feature | Indicator | Value | Class | Direction
--------------------------------------------------------
1     |  WPS     |     <=    | 0.27  | 4     | 1 -> 2  
--------------------------------------------------------
2     |  WPS     |     >     | 0.27  | 5     | 1 -> 3
--------------------------------------------------------
3     |  CXC     |     <=    | 0.45  | 2     | 2 -> 4
--------------------------------------------------------
4     |  CXC     |     >     | 0.45  | 1     | 2 -> 5
--------------------------------------------------------
5     |  KPL     |     <=    | 0.30  | 3     | 3 -> 5
--------------------------------------------------------
6     |  KPL     |     >     | 0.30  | 5     | 3 -> 1

So every second row changes the 'Feature' and 'Value' into the same as the row above, and the 'Indicator' is changed to '>'

I can't figure out how to iterate through the Dataframe (using iterrows I suppose) and changing only every second row?

EDIT:

I have tried the following as recommended:

    my_df = pd.DataFrame()my_df['N'] = [1, 2, 3, 4, 5, 6]my_df['I'] = ['=>', '=>', '=>', '=>', '=>', '=>']my_df['F'] = ['a', 'b', 'c', 'd', 'e', 'f']my_df.loc[1::2, 'F'] = Nonemy_df.loc[1::2, 'I'] = '>'my_df.fillna(method='ffill')print(my_df)

Output:

   N   I     F
0  1  =>     a
1  2   >  None
2  3  =>     c
3  4   >  None
4  5  =>     e
5  6   >  None
Answer

Find below is the logic used

  • Select the even rows using slicing.
  • Set the desired columns / fields with None for the sliced rows which need to be borrowed from previous row, we can fill it later using forward fill.
  • Then use forward fill from last non null fields for respective columns
import pandas as pd
xlsColName = chr(ord('A')+colPosn)       # Get xls column name (not the column header as per data frame). This will be used to set attributes of xls columns
df = pd.read_csv('temp.csv')
df.loc[1::2, 'Feature'] = None           # prepare the field for use with df.fillna
df.loc[1::2, 'Value'] = None
df.loc[1::2, 'Indicator'] = '>'          # update the indicator field
df.fillna(method='ffill', inplace=True)  # This fills the NaN values from existing values 
https://en.xdnf.cn/q/119608.html

Related Q&A

Why is the list index out of range?

Im new at programing and Im trying to check a piece of code that keeps giving me this error: t[i] = t[i - 1] + dt IndexError: list index out of rangeThe code is the following: dt = 0.001t = [0] for i i…

Stopping a while loop mid-way - Python

What is the best way to stop a while loop in Python mid-way through the statement? Im aware of break but I thought using this would be bad practice.For example, in this code below, I only want the pro…

Click on element in dropdown with Selenium and Python

With Selenium and Chrome webdriver on MacOS need to click dropdown element. But always have an error that cant find. Have this html code on a page where it located:<select id="periodoExtrato&qu…

Send cv2 video stream for face recognition

Im struggling with a problem to send a cv2 videostream (webcam) to a server (which shall be used later for face recognition). I keep getting the following error for the server: Traceback (most recent c…

Generate all possible lists from the sublist in python [duplicate]

This question already has answers here:How to get the Cartesian product of multiple lists(20 answers)Closed 7 years ago.Suppose I have list [[a, b, c], [d, e], [1, 2]]I want to generate list where on t…

Time/frequency color map in python

Is there in native Python 3.X library or in scipy/numpy/matplolib libraries a function or their short set which could help me to draw a plot similar to this one(?):What would be an efficient way to ac…

ImageMagick is splitting the NASAs [.IMG] file by a black line upon converting to JPG

I have some raw .IMG format files which Im converting to .jpg using ImageMagick to apply a CNN Classifier. The converted images, however have a black vertical line splitting the image into two. The par…

CV2 - rectangular detecting issue

Im trying to implement an OMR using pythons CV2. As part of the code I need to find the corners of the choices box (rectangulars) however I ran into difficulty causes by the grade sheet template. In th…

Keras/TensorFlow - high acc, bad prediction

Im new to machine learning and Im trying to train a model which detects Prague city in a sentence. It can be in many word forms.Prague, PRAHA, Z Prahy etc...So I have a train dataset which consists of …

Flask-HTTPAuth: how to pass an extra argument to a function decorated with @auth.verify_password?

Heres a small Flask app authenticated with Flask-HTTPAuth. How to pass an argument (such as authentication on/off flag, or verbosity level / debug on/off flag) to a function (such as authenticate below…