1

I am trying to add the same column when creating a new Pandas DataFrame in Python. I am trying to do something like the following:

I am trying to make all columns of the DataFrame above the same list. Is it possible to do this for a list of integers (or more generally, a list of strings/objects/etc.)?

I've tried using arrays, dicts, lists for column names. This part is something I can figure out, but figuring out a scalable way to just pass in one list is what I am trying to figure out.

column_names = array(['col0', 'col1', 'col2', 'col3'], dtype=object)
some_list = [int0, int1, int2]

df = pd.DataFrame(some_list, columns=column_names)

I would like to see something like:

  col0 col1 col2 col3

0 int0 int0 int0 int0
1 int1 int1 int1 int1
2 int2 int2 int2 int2

1 Answer 1

3

IIUC, consider not using list as a variable (or any other reserved keyword), since list is a built in function and you will override it.

l = [0, 1, 2]
df = pd.DataFrame(dict.fromkeys(column_names,l))
df
   col0  col1  col2  col3
0     0     0     0     0
1     1     1     1     1
2     2     2     2     2

Another method

pd.DataFrame([l]*len(column_names),index=column_names).T
   col0  col1  col2  col3
0     0     0     0     0
1     1     1     1     1
2     2     2     2     2
Sign up to request clarification or add additional context in comments.

7 Comments

Yup I forgot to use a different variable name. Edited now.
Thanks for the help! How does this compare to other methods? For example, are there other methods besides using dict.fromkeys(column_names, some_list) and how would it compare (in terms of memory, time, etc.)?
@qxzsilver I would say , they almost the same, since you need to get the input data as same size of columns you want to build
@qxzsilver if this help , would u like accept and upvote ?
This helped a lot! However, the dict.fromkeys(col_names, some_list) had the unwanted side effect of re-arranging the column names by alphabetical order for the column names within the DataFrame. Is there another workaround besides dictionary, since dictionary seems to arrange by column_names within memory.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.