Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create multiple rows of a data frame based on some original values

I am a Python newbie and have a question.

As a simple example, I have three variables:

a = 3
b = 10
c = 1

I’d like to create a data frame with three columns (‘a’, ‘b’, and ‘c’) with:
each column +/- a certain constant from the original value AND also >0 and <=10.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If the constant is 1 then:
the possible values of ‘a’ will be 2, 3, 4
the possible values of ‘b’ will be 9, 10
the possible values of ‘c’ will be 1, 2

The final data frame will consist of all possible combination of a, b and c.

enter image description here

Do you know any Python code to do so?

Here is a code to start.

import pandas as pd

data = [[3 , 10, 1]]
    
df1 = pd.DataFrame(data, columns=['a', 'b', 'c'])

>Solution :

You may use itertools.product for this.

Create 3 separate lists with the necessary accepted data. This can be done by calling a method which will return you the list of possible values.

def list_of_values(n):
    if 1 < n < 9:
        return [n - 1, n, n + 1]
    elif n == 1:
        return [1, 2]
    elif n == 10:
        return [9, 10] 
    return []

So you will have the following:

a = [2, 3, 4]
b = [9, 10]
c = [1,2]

Next, do the following:

from itertools import product
l = product(a,b,c)

data = list(l)

pd.DataFrame(data, columns =['a', 'b', 'c'])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading