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

Question:

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.

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'])
Asked By: Ketty

||

Answers:

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'])
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.