Pandas:在一个索引上将多行合并为一列
Pandas: merging multiple rows into one column on one index
我有一个值字典:
d = {
0: [1.61122, 1.61544, 1.60593, 1.60862, 1.61386],
3: [1.61962, 1.61734, 1.6195],
1: [1.5967, 1.59462, 1.59579],
2: [1.59062, 1.59279],
}
我想在 pandas 中创建一个 table,其中字典的键是索引,每个索引都有包含字典值的多行,如下所示:
什么方法或工具可以让我制作这样的 table?
使用 Series 构造函数和 explode
:
df = pd.Series(d).explode().reset_index(name='price')
输出:
index price
0 0 1.61122
1 0 1.61544
2 0 1.60593
3 0 1.60862
4 0 1.61386
5 3 1.61962
6 3 1.61734
7 3 1.6195
8 1 1.5967
9 1 1.59462
10 1 1.59579
11 2 1.59062
12 2 1.59279
我有一个值字典:
d = {
0: [1.61122, 1.61544, 1.60593, 1.60862, 1.61386],
3: [1.61962, 1.61734, 1.6195],
1: [1.5967, 1.59462, 1.59579],
2: [1.59062, 1.59279],
}
我想在 pandas 中创建一个 table,其中字典的键是索引,每个索引都有包含字典值的多行,如下所示:
什么方法或工具可以让我制作这样的 table?
使用 Series 构造函数和 explode
:
df = pd.Series(d).explode().reset_index(name='price')
输出:
index price
0 0 1.61122
1 0 1.61544
2 0 1.60593
3 0 1.60862
4 0 1.61386
5 3 1.61962
6 3 1.61734
7 3 1.6195
8 1 1.5967
9 1 1.59462
10 1 1.59579
11 2 1.59062
12 2 1.59279