I am trying to create a table in Pandas and I want my columns to be titled by the numbers between 0 and 56, but typing them by myself is very inefficient.
Here is my code:
import pandas as pd
x = [i for i in range(57)]
df = pd.DataFrame(data=x,columns=["0", "1", "2", ... "56"])
I'd rather use something more efficient, so I tried:
import pandas as pd
x = [i for i in range(57)]
y = [i for i in range(57)]
df = pd.DataFrame(data=x,columns=[y])
This will give me an ValueError
. I've also tried much, much more, but the best I could get was the whole list as one column. I looked through the official Pandas website and so on but didnt found a solution to my problem without using Excel. So do you have an idea how I can reach my goal only using NumPy, Pandas and Python?
CodePudding user response:
You need x
to be 2D and y
1D (notice the square brackets):
import pandas as pd
x = [i for i in range(57)]
y = [i for i in range(57)]
df = pd.DataFrame(data=[x], columns=y)
Output:
0 1 2 3 4 5 6 7 8 9 ... 47 48 49 50 51 52 53 \
0 0 1 2 3 4 5 6 7 8 9 ... 47 48 49 50 51 52 53
54 55 56
0 54 55 56
[1 rows x 57 columns]
NB. If you really want names from 0 to n, just omit the "columns" parameter as this will be the default
CodePudding user response:
By default, column names are listed from 0 .. N
import numpy as np
import pandas as pd
df = pd.DataFrame(np.arange(57)[None,:])
Result:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 ... 43 44 45 46 47 48 49 50 51 52 53 54 55 56
0 0 1 2 3 4 5 6 7 8 9 10 11 12 13 ... 43 44 45 46 47 48 49 50 51 52 53 54 55 56
[1 rows x 57 columns]