【发布时间】:2021-12-20 13:55:22
【问题描述】:
我有这样的数据框:
Col1 col2 col3
test0 [1,2,3] [ab,bc,cd]
我想要的输出数据框是:
col1 col2 col3
test0 1 ab
test0 2 bc
test0 3 cd
会有多个列,如 col2,列表长度相同
【问题讨论】:
-
看看explode
我有这样的数据框:
Col1 col2 col3
test0 [1,2,3] [ab,bc,cd]
我想要的输出数据框是:
col1 col2 col3
test0 1 ab
test0 2 bc
test0 3 cd
会有多个列,如 col2,列表长度相同
【问题讨论】:
你可以这样做:
outputdf_expandedcols=pd.DataFrame({
"col2":df.apply(lambda x: pd.Series(x['col2']),axis=1).stack().reset_index(level=1, drop=True),
"col3":df.apply(lambda x: pd.Series(x['col3']),axis=1).stack().reset_index(level=1, drop=True)
})
outputdf = df[['Col1']].join(outputdf_expandedcols,how='right')
outputdf 将是:
Col1 col2 col3
0 test0 1 ab
0 test0 2 bc
0 test0 3 cd
如果您有更多列要扩展,您可以使用dict comprehension:
list_of_cols_to_expand = ["col2", "col3"] # put here the column names you want to expand
outputdf_expandedcols=pd.DataFrame({
col:df.apply(lambda x: pd.Series(x[col]),axis=1).stack().reset_index(level=1, drop=True) for col in list_of_cols_to_expand
})
outputdf = df[['Col1']].join(outputdf_expandedcols,how='right')
输出同上。
此答案基于this 线程。
【讨论】:
如果你有最新版本的 pandas,你也可以这样做:
cols_to_expand = ["col2", "col3"] # or more columns if you have more
outputdf = df.explode(cols_to_expand)
outputdf 将是:
Col1 col2 col3
0 test0 1 ab
0 test0 2 bc
0 test0 3 cd
要在 Google Colab 中拥有兼容的 Pandas 版本,您需要运行一个单元格(基于 this):
%%shell
pip install --upgrade --force-reinstall pandas
pip install -I pandas
pip install --ignore-installed pandas
然后重启内核(点击Runtime,然后点击Restart runtime)。
【讨论】: