[英]Insert list of lists into single column of pandas df
I am trying to place multiple lists into a single column of a Pandas df.我正在尝试将多个列表放入 Pandas df 的单个列中。 My list of lists is very long, so I cannot do so manually.
我的列表很长,所以我不能手动这样做。
The desired out put would look like this:所需的输出将如下所示:
list_of_lists = [[1,2,3],[3,4,5],[5,6,7],...]
df = pd.DataFrame(list_of_lists)
>>> df
0
0 [1,2,3]
1 [3,4,5]
2 [5,6,7]
3 ...
Thank you for the assistance.感谢您的帮助。
You can assign it by wrapping it in a Series
vector if you're trying to add to an existing df
:如果您尝试添加到现有
df
则可以通过将其包装在Series
向量中来分配它:
In [7]:
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randn(5,3), columns=list('abc'))
df
Out[7]:
a b c
0 -1.675422 -0.696623 -1.025674
1 0.032192 0.582190 0.214029
2 -0.134230 0.991172 -0.177654
3 -1.688784 1.275275 0.029581
4 -0.528649 0.858710 -0.244512
In [9]:
df['new_col'] = pd.Series([[1,2,3],[3,4,5],[5,6,7]])
df
Out[9]:
a b c new_col
0 -1.675422 -0.696623 -1.025674 [1, 2, 3]
1 0.032192 0.582190 0.214029 [3, 4, 5]
2 -0.134230 0.991172 -0.177654 [5, 6, 7]
3 -1.688784 1.275275 0.029581 NaN
4 -0.528649 0.858710 -0.244512 NaN
关于什么
df = pd.DataFrame({0: [[1,2,3],[3,4,5],[5,6,7]]})
The above solutions were helpful but wanted to add a little bit in case they didn't quite do the trick for someone...上面的解决方案很有帮助,但我想补充一点,以防它们对某人没有多大用处……
pd.Series will not accept a np.ndarray that looks like a list-of-lists, eg one-hot labels array([[1, 0, 0], [0, 1, 0], ..., [0, 0, 1]])
. pd.Series 不会接受看起来像列表列表的 np.ndarray,例如 one-hot labels
array([[1, 0, 0], [0, 1, 0], ..., [0, 0, 1]])
。
So in this case one can wrap the variable with list()
:所以在这种情况下,可以用
list()
包装变量:
df['new_col'] = pd.Series(list(one-hot-labels))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.