简体   繁体   中英

IndexError: list index out of range. Can anyone help me out with this Python code ? Includes concepts of numpy and pandas

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.

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'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM