0

I am working in Python. I have a dataframe called df with 3 columns: a, b, c. I want to do a loop which loops through all variables and generates a numpy array for each variable and cuts the last number of each variable. So far I have tried, but it is not working:

df = pd.DataFrame(
    [[1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]],
    columns=['a', 'b', 'c'])
    variables= [a,b,c]
    for x in variables:
        x  = np.transpose(np.matrix(df.x.to_numpy(np.float64)))
        x=x[:-1]
Alex
  • 29
  • 1
  • 6
  • 1
    How about simply `for col in df.columns: ... df[col]...`? – 0x5453 Jan 19 '21 at 20:55
  • Note that you are reassigning your loop variable `x`, which probably isn't what you want. – 0x5453 Jan 19 '21 at 20:56
  • I do want to generate 3 variables called a,b and c. This is probably not optimal but I have the rest of the code generated like this... – Alex Jan 19 '21 at 20:57
  • `df.to_numpy()` produces a 2d array, `df.x` is series, and result is 1d. Why `np.matrix` and `transpose`? If you want to assign the the elements of some array to 3 variables use `unpacking`, `a,b,c = np.array([1,2,3])`. – hpaulj Jan 19 '21 at 21:40

1 Answers1

0

From comments:

I do want to generate 3 variables called a,b and c. This is probably not optimal but I have the rest of the code generated like this

It sounds like what you're really asking here is how to dynamically set a variable name to match an arbitrary character string.

If you reeeeallly want to do that, this question and its chain of duplicates will give you some options.

But I would strongly STRONGLY encourage you to look for other ways of doing this. A dict is the most obvious option. If the rest of your code requires it, you're probably best off fixing up the rest of your code.