我正在尝试迭代一个包含一些数字并希望保存到数据框的列表。
但是在尝试了set_values
和concat
之后(这更加困难)。我无法获得合适的解决方案。另一个问题是它必须在读取“END”之前停止...
列表和数据框如下:
words= ['302', '1208', '1208', '0', '179', '1208', '1208', '0', '904', '233', '233', '0', '***END', 'OF', 'REPORT***']
dd = pd.DataFrame(columns=("AA","BB","CC","DD"))
以及我到目前为止使用的代码:
for r in range(40,48,4):
for s in range(41,49,4):
for t in range(42,50,4):
for z in range(43,51,4):
dd = dd.set_value(len(dd),'AA',words[r])
dd = dd.set_value(len(dd),'BB',words[s])
dd = dd.set_value(len(dd),'CC',words[t])
dd = dd.set_value(len(dd),'DD',words[z])
我想返回如下所示的内容:
AA | BB | CC | DD |
302|1208|1208|0 |
最佳答案
对我来说,concat
是最后的手段。它不可避免地会变得毛茸茸的。而且,就其值(value)而言,我认为我从未使用过 set_value
——它很少需要变得如此精细。
这是一个解决方案。
In [10]: numbers = np.array(words[:words.index('***END')]).astype('int')
In [11]: columns = ['AA', 'BB', 'CC', 'DD']
In [12]: dd = DataFrame(numbers.reshape(-1, 4), columns=columns)
In [13]: dd
Out[13]:
AA BB CC DD
0 302 1208 1208 0
1 179 1208 1208 0
2 904 233 233 0
(如果 -1
对您来说是新的,请参阅 documentation for reshape 。)
关于python - Pandas Dataframe Append 或 Set_Value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17054488/