Home > Mobile >  Adding multiple constant values in a pandas dataframe column
Adding multiple constant values in a pandas dataframe column

Time:09-17

I would like to know how to add multiple constant values of different lengths into a dataframe column. I know that we can add a single constant value (for example: 5) to a data frame column 'A' like this:

df['A'] = 5

But I want to have the dataframe something like the table below. As you can see, I need three 5s, two 10s, six 30s and one 100s. How can you do that for maybe 10000 rows with a set number of values (not random) each having a user defined frequency.

index A
1 5
2 5
3 5
4 10
5 10
6 30
7 30
8 30
9 30
10 30
11 30
12 100

CodePudding user response:

IIUC you could just use:

df['b'] = np.repeat([5, 5, 5, 10, 10, 30, 30, 30, 30, 30, 30, 100], np.ceil(len(df) / 12))[:len(df)]

Or:

df['b'] = np.repeat([*[5] * 3, *[10] * 2, *[30] * 6, 100], np.ceil(len(df) / 12))[:len(df)]

CodePudding user response:

You can use numpy.repeat with the DataFrame constructor:

vals = [5,10,30,100]
reps = [3,2,6,1]
df = pd.DataFrame({'A': np.repeat(vals, reps)})
df.index =1

output:

      A
1     5
2     5
3     5
4    10
5    10
6    30
7    30
8    30
9    30
10   30
11   30
12  100

CodePudding user response:

Try this:

import itertools

value  = [5,10,30,100]
repeat = [3,2,6,1]

lst = [([v]*r) for v,r in zip(value,repeat)]

merged = list(itertools.chain(*lst))

df = pd.DataFrame({'A':merged})
df

Output:

      A
0     5
1     5
2     5
3    10
4    10
5    30
6    30
7    30
8    30
9    30
10   30
11  100

CodePudding user response:

You can specify values and repeats in dictionary and use:

d = {3:5, 2:10, 6:30, 1:100}
df = pd.DataFrame({'A': [x for k, v in d.items() for x in [v] * k]})
print (df)
      A
0     5
1     5
2     5
3    10
4    10
5    30
6    30
7    30
8    30
9    30
10   30
11  100

Solution with dictionary and numpy.repeat:

df = pd.DataFrame({'A': np.repeat(list(d.values()), list(d.keys()))})
print (df)
      A
0     5
1     5
2     5
3    10
4    10
5    30
6    30
7    30
8    30
9    30
10   30
11  100
  • Related