我正在尝试将多个列表放入熊猫 df 的单个列中。 我的列表很长,所以我无法手动执行此操作。
所需的输出如下所示:
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 ...
感谢您的帮助。
如果您尝试添加到现有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]]})
上述解决方案很有帮助,但想添加一点,以防他们没有完全为某人解决问题......
PD.系列将不接受看起来像列表列表的 np.ndarray,例如 one-hot 标签array([[1, 0, 0], [0, 1, 0], ..., [0, 0, 1]])
。
所以在这种情况下,可以用 list()
包装变量:
df['new_col'] = pd.Series(list(one-hot-labels))