【发布时间】:2021-05-07 21:55:49
【问题描述】:
这可能是重复的,但我找不到所需的答案。 那么问题来了:
假设,我有一个这样的数据框:
d1 = {'col1': [[1],[2,3]],
'col2' : [[3],[21,1]]}
df1 = pd.DataFrame(d1)
| col1 | col2 | |
|---|---|---|
| 0 | [1] | [3] |
| 1 | [2, 3] | [21, 1] |
现在,我们可以通过df1.apply(pd.Series.explode) 轻松地垂直扩展这个数据框。
但是,横向扩展和更改列名最优雅的方式是什么?
类似这样的:
d2 = {
'col1_1':[1,2],
'col1_2': [np.NAN,3],
'col2_1' : [3,21],
'col2_2' : [np.NAN,1]
}
df2 = pd.DataFrame(d2)
输出:
| col1_1 | col1_2 | col2_1 | col2_2 | |
|---|---|---|---|---|
| 0 | 1 | NaN | 3 | NaN |
| 1 | 2 | 3.0 | 21 | 1.0 |
【问题讨论】:
标签: python python-3.x pandas dataframe pandas-groupby