2
list = [[1,1,56],
        [20,2,78],
        [30,3,34],
        [40,4,98]]

this is my list of list and i want to make a dataframe like this-;

a  b  c
1  1  56
20 2  78
30 3  34
40 4  98

i did a code

df = pd.DataFrame(list) df = df.transpose() df.columns = ["a", "b", "c"]

it gives me a error like Length mismatch: Expected axis has 4 elements, new values have 3 elements

please help me thanks in advance

5
  • 1
    remove the transpose line and it will work as expected Commented Feb 6, 2019 at 7:30
  • 2
    Why not df = pd.DataFrame(L, columns=["a", "b", "c"]) ? Commented Feb 6, 2019 at 7:30
  • Remove the transpose. df = pd.DataFrame(list) gives you a df of dimensions (4 rows, 3 cols). Transpose changes it to (3 rows, 4 cols) and then you will have to 4 col names instead of three. Commented Feb 6, 2019 at 7:31
  • what @jezarel suggested is the proper way to do it Commented Feb 6, 2019 at 7:32
  • all of you guys , thanks a lot Commented Feb 6, 2019 at 7:35

1 Answer 1

3

First dont use list because reserved code word in python and then only pass columns parameter, transpose is not necessary:

L = [[1,1,56],
      [20,2,78],
      [30,3,34],
      [40,4,98]]

df = pd.DataFrame(L, columns=["a", "b", "c"])
print (df)
    a  b   c
0   1  1  56
1  20  2  78
2  30  3  34
3  40  4  98
Sign up to request clarification or add additional context in comments.

3 Comments

and if i want to convert that (dataframe into list of list) , how can we do that?
Use L = df.values.tolist()
amazing bro, take a HUG from my-side<3

Your Answer

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