python - 从嵌入列中的列表中提取元素
问题描述
我有以下数据框:
col1 col2
[12, 2] 4
[2, 5] 3
我要这个:
col1A col1B col2
12 2 4
2 5 3
这个问题与此类似,但在执行 df['col1'].str[0]
时,我将其作为输出:
col1 col2
[ 4
[ 3
解决方案
采用:
new_df=df.T.apply(lambda x: x.explode()).T
print(new_df)
col1 col1 col2
0 12 2 4
1 2 5 3
如果要重命名列,请使用:
df2=df.T.apply(lambda x: x.explode())
groups=df2.groupby(level=0)
letters=groups.cumcount().map({0:'A',1:'B'})
df2.index=(df2.index+letters).where(groups.size()>1,df2.index.to_series())
new_df=df2.T
print(new_df)
col1A col1B col2
0 12 2 4
1 2 5 3
推荐阅读
- ios - 如何在不重新加载Objective-C中的行的情况下更改行中的特定元素?
- java - 如何使用 AlarmManager 设置一些警报?
- r - 具有不同 y 轴刻度的 ggplot facet_grid:分面面板的反向轴
- javascript - 如何将对象的属性映射到另一个对象?
- python - 在 Python 中清理临时文件目录
- linux - Can I block a new process execution using Kprobe?
- javascript - 为什么不能分离 xmlHttp.onreadystatechange 的函数?
- java - 从二维数组生成嵌套的 HashMap 列表
- javascript - 下拉菜单中的错误
- python - python django sort with lambda with if 语句