我是Python的新手,正在研究numpy和pandas的基本用法。我使用VS Code作为我的源代码编辑器。代码如下:
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)
我得到的输出是:
(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
有人能帮我吗?我期待一个由上面代码中的硬编码值指定的随机值的Dataframe列表。
发布于 2019-12-11 14:31:31
错误出在这一行--列列表应该是一个字符串列表。此时,您可以尝试将列表本身分配给列名。
df = pd.DataFrame(data = a, columns = ['temp', 'name', 'random'])
https://stackoverflow.com/questions/59288014
复制相似问题