2

I am new to Python and is working on the basic use of numpy and pandas. I am using VS Code as my source code editor. The code is as follows :

import numpy as np
import pandas as pd

temp = np.random.randint(low = 20, high = 100, size = [20,])
name = np.random.choice(['A','Python','Excel','B'], 20)
random = np.random.choice([10,11,12,13,14], 20)

a = list(zip(temp, name, random))
df = pd.DataFrame(data = a, columns = [temp, name, random])
print(df)

And the output I am getting is :

(work) PS C:\DEV> & c:/DEV/work/Scripts/python.exe c:/DEV/Num.py
Traceback (most recent call last):
  File "c:/DEV/Num.py", line 9, in <module>
(work) PS C:\DEV> & c:/DEV/work/Scripts/python.exe c:/DEV/Num.py
Traceback (most recent call last):
  File "c:/DEV/Num.py", line 9, in <module>
    df = pd.DataFrame(data = a, columns = [temp, name, random])
  File "C:\DEV\work\lib\site-packages\pandas\core\frame.py", line 462, in __init__
    mgr = arrays_to_mgr(arrays, columns, index, columns, dtype=dtype)
  File "C:\DEV\work\lib\site-packages\pandas\core\internals\construction.py", line 87, in 
arrays_to_mgr
    return create_block_manager_from_arrays(arrays, arr_names, axes)
  File "C:\DEV\work\lib\site-packages\pandas\core\internals\managers.py", line 1694, in 
create_block_manager_from_arrays
    blocks = form_blocks(arrays, names, axes)
  File "C:\DEV\work\lib\site-packages\pandas\core\internals\managers.py", line 1745, in form_blocks
    v = arrays[name_idx]
IndexError: list index out of range

Can anyone help me out? I am expecting a Dataframe list of random values, specified by the above hardcoded values in my code.

2
  • 3
    maybe columns=['temp', 'name', 'random']? Commented Dec 11, 2019 at 14:31
  • Thanks a lot man. Never guessed it could be time this simple. Commented Dec 11, 2019 at 14:34

1 Answer 1

2

The error is with this line - the columns list should be a list of strings. At the moment, you try to assign the lists themselves to the column names.

df = pd.DataFrame(data = a, columns = ['temp', 'name', 'random'])
Sign up to request clarification or add additional context in comments.

Comments

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.