Home > Enterprise >  Create an array of values with a given formula
Create an array of values with a given formula

Time:09-23

In Python I would like to create a dataframe out of a list of values: the column names are numbers from 1 to 500. The y-index are numbers from 300 to 14000. The values of the list should be filled with a formula calculation depending on the column name and the row index:

v = 2 * PI * x / index

so that the result is like this list:

index      1            2           3           4           5           ... 500
300        0.020943951  0.041887902 0.062831853 0.083775804 0.104719755 ... 10.47197551
...        ...          ...         ...         ...         ...         ... ...
14000      0.000448799  0.000897598 0.001346397 0.001795196 0.002243995 ... 0.224399475

The x names I would create with

import numpy as np

x = np.array(range(1,501,1))

the index number I would create the same way:

y = np.array(range(300, 14001,1))

Now I get stuck with the filling by the formula. How do I realize the calculation depending of row index and column name value? This snippet does not work (line 19, in v = 2* np.pi * x / y TypeError: can't multiply sequence by non-int of type 'float'):

data = []

for a in y:
    for b in x:
        v = 2* np.pi * x / y
        data.append(v)
data.append(v)

Finally I would create the dataframe:

import pandas as pd
df = pd.DataFrame([array content of the calculation], index = y, columns = x)

CodePudding user response:

You can use broadcasting of numpy arrays to generate your data, then convert the product into a dataframe. Here's a small example:

x = np.arange(1, 5)
y = np.arange(300,304)
res = 2 * np.pi * x[np.newaxis, :] / y[:, np.newaxis]
df = pd.DataFrame(res, columns=x, index=y)
print(df)

Output:

            1         2         3         4
300  0.020944  0.041888  0.062832  0.083776
301  0.020874  0.041749  0.062623  0.083497
302  0.020805  0.041610  0.062416  0.083221
303  0.020737  0.041473  0.062210  0.082946
  • Related