如何将 DataFrame 转换为列表?
How to convert a DataFrame to a List?
我有一个包含三列的 DataFrame。我想将此 DataFrame 转换为 python 列表。
数据框:
name year value
0 val_1 2001 3
1 val_1 2002 3
2 val_2 2001 0
3 val_2 2002 3
4 val_3 2001 3
5 val_3 2002 0
6 val_4 2001 np.nan
列表:
[['val_1', [[2001, 3], [2002, 3]]], ['val_2', [[2001, 0], [2002, 3]]], ['val_3', [[2001, 3], [2002, 0]]], ['val_4', []]]
一次尝试:
[[k, list(g.values[:, 1:].tolist())] for k, g in df.groupby('value')]
(我很难应付np.nan)
尝试:
>>> [[k, v.drop("name",axis=1).dropna().astype('int').to_numpy().tolist()] for k, v in df.groupby('name')]
[['val_1', [[2001, 3], [2002, 3]]],
['val_2', [[2001, 0], [2002, 3]]],
['val_3', [[2001, 3], [2002, 0]]],
['val_4', []]]
另一个版本:
x = [[i, g[g.notna().all(1)].values[:, 1:].tolist()] for i, g in df.groupby("name")]
print(x)
打印:
[
["val_1", [[2001, 3.0], [2002, 3.0]]],
["val_2", [[2001, 0.0], [2002, 3.0]]],
["val_3", [[2001, 3.0], [2002, 0.0]]],
["val_4", []],
]
我有一个包含三列的 DataFrame。我想将此 DataFrame 转换为 python 列表。
数据框:
name year value
0 val_1 2001 3
1 val_1 2002 3
2 val_2 2001 0
3 val_2 2002 3
4 val_3 2001 3
5 val_3 2002 0
6 val_4 2001 np.nan
列表:
[['val_1', [[2001, 3], [2002, 3]]], ['val_2', [[2001, 0], [2002, 3]]], ['val_3', [[2001, 3], [2002, 0]]], ['val_4', []]]
一次尝试:
[[k, list(g.values[:, 1:].tolist())] for k, g in df.groupby('value')]
(我很难应付np.nan)
尝试:
>>> [[k, v.drop("name",axis=1).dropna().astype('int').to_numpy().tolist()] for k, v in df.groupby('name')]
[['val_1', [[2001, 3], [2002, 3]]],
['val_2', [[2001, 0], [2002, 3]]],
['val_3', [[2001, 3], [2002, 0]]],
['val_4', []]]
另一个版本:
x = [[i, g[g.notna().all(1)].values[:, 1:].tolist()] for i, g in df.groupby("name")]
print(x)
打印:
[
["val_1", [[2001, 3.0], [2002, 3.0]]],
["val_2", [[2001, 0.0], [2002, 3.0]]],
["val_3", [[2001, 3.0], [2002, 0.0]]],
["val_4", []],
]