[英]How to solve IndexError: list index out of range?
I have the following piece of code: 我有以下代码:
s = output.set_index('name')['col1']
df = pd.DataFrame(s.values.tolist(), index=s.index).stack().reset_index()
The second line raises an error: 第二行引发错误:
IndexError: list index out of range
I just want to understand why it happens? 我只想了解它为什么会发生?
The s.index
returns: s.index
返回:
Index(['100100', '100200', '100300'], dtype='object', name='name')
The s.values.tolist()
returns: s.values.tolist()
返回:
[
[],
[],
[]
]
Update: 更新:
This is an example of s
. 这是s
一个例子。 It should be a starting point. 这应该是一个起点。
col1
a []
b []
c []
d ["c1","c2"]
When col1
is empty in all rows, the code fails at df = pd.DataFrame(s.values.tolist(), index=s.index).stack().reset_index()
. 当col1
在所有行中为空时,代码在df = pd.DataFrame(s.values.tolist(), index=s.index).stack().reset_index()
。
This code fails for me (python 3.7 and pandas 0.24.2): 这段代码对我来说失败了(python 3.7和pandas 0.24.2):
s = pd.DataFrame({'name':['a','b','c'],
'col1': [[],[],[]]}).set_index('name')
s.col1.apply(pd.Series).stack().dropna().reset_index()
The goal is to get either empty DataFrame if all col1 values are [], or the following DataFrame (for the above-shown example of s
): 如果所有col1值都是[],则目标是获取空DataFrame,或者使用以下DataFrame(对于上面显示的s
示例):
df =
name col1
d c1
d c2
s.values.tolist()
gives [[], [], [], ['c1', 'c2']]
, which is not really what you want. s.values.tolist()
给出[[], [], [], ['c1', 'c2']]
,这不是你想要的。 I think you need pd.Series
instead of tolist
: 我认为你需要pd.Series
而不是tolist
:
s = pd.DataFrame({'name':['a','b','c','d','e'],
'col1': [[],[],[],['c1','c2'],['d','e','f']]}).set_index('name')
s.col1.apply(pd.Series).stack().dropna().reset_index()
Output: 输出:
+---+------+---------+----+
| | name | level_1 | 0 |
+---+------+---------+----+
| 0 | d | 0 | c1 |
| 1 | d | 1 | c2 |
| 2 | e | 0 | d |
| 3 | e | 1 | e |
| 4 | e | 2 | f |
+---+------+---------+----+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.