python - 大熊猫中的爆炸列表列
问题描述
考虑以下示例
dftest = pd.DataFrame({'mylist1' : [['hello', 'hasta'], 'one'],
'mylist2' : [['there', 'la vista'], 'shot']})
dftest
Out[240]:
mylist1 mylist2
0 [hello, hasta] [there, la vista]
1 one shot
我想分解这两列,以便将 in 中的第 n 个元素mylist1
连接到 中的第 n 个元素mylist2
。Mylist1
并且mylist2
始终具有相同数量的元素(在此示例中:第一个 obs 中为 2,第二个 obs 中为 1)。
所需的输出如下所示。如您所见hello
,与 匹配there
、hasta
与 匹配la vista
等。我们获得了三行,因为第一个列表中有两个元素,而第二个列表中只有一个。
Out[241]:
exploded
0 hello there
1 hasta la vista
2 one shot
我怎样才能做到这一点?谢谢!
解决方案
这是一种方法:
Explode
数据框vertically
join
沿轴的字符串1
。
df = df.apply(pd.Series.explode).apply(' '.join, 1)
输出:
0 hello there
0 hasta la vista
1 one shot
dtype: object
推荐阅读
- android - 添加新项目后滚动到 RecyclerView 中的第一个元素
- mysql - 如何在另一个 SQL 查询中使用 SQL 查询的结果
- javascript - 如何匹配数组中的变量并将匹配项附加一个数字并将其添加到数组中?
- julia - 如何让 Travis CI 使用 SSH 密钥:目前在访问我的私人代表时卡住了(想要用户名)
- css-selectors - 如何使用量角器查找特定的子元素
- python-3.x - Pandas .apply() 函数并不总是在 python 3 中被调用
- python - 每个线程 run() 函数增加并打印一个变量会产生奇怪的结果
- c# - 如何插入具有自定义多对多关联的实体框架?
- php - 从同一张表之间的关系中提取primaryKey
- sql-server - 动态计算日期列 MS SQL Server 中所有行的 DateDiff