gpt4 book ai didi

python - 如何将字符串拆分为字符矩阵

转载 作者:行者123 更新时间:2023-11-30 22:22:12 24 4
gpt4 key购买 nike

假设我们在 Python 中有这个数组:

import pandas as pd
arr = pd.DataFrame(['aabbc','aabccca','aa'])

我想将每一行拆分为其字符的列。行的长度可能不同。这是我期望的输出(在本例中为 3*7 矩阵):

  1   2   3   4   5   6   7
1 a a b b c Na Na
2 a a b c c c a
3 a a Na Na Na Na Na

我的矩阵的行数是 20000,我不喜欢使用 for 循环。原始数据是蛋白质序列。我读过[1] , [2] , [3]等等,他们没有帮助我。

最佳答案

选项 1
一种简单的方法是使用列表理解。

pd.DataFrame([list(x) for x in arr[0]])

0 1 2 3 4 5 6
0 a a b b c None None
1 a a b c c c a
2 a a None None None None None

或者,使用 apply(list) 执行相同的操作。

pd.DataFrame(arr[0].apply(list).tolist())

0 1 2 3 4 5 6
0 a a b b c None None
1 a a b c c c a
2 a a None None None None None
<小时/>

选项 2
可以使用 extractall + unstack 替代。您最终将得到列的多重索引。您可以删除结果的第一级。

v = arr[0].str.extractall(r'(\w)').unstack()
v.columns = v.columns.droplevel(0)

v

match 0 1 2 3 4 5 6
0 a a b b c None None
1 a a b c c c a
2 a a None None None None None
<小时/>

选项 3
操作 View -

v = arr[0].values.astype(str)
pd.DataFrame(v.view('U1').reshape(v.shape[0], -1))

0 1 2 3 4 5 6
0 a a b b c
1 a a b c c c a
2 a a

这会为您提供空字符串 (''),而不是单元格中的 None。如果您想将它们添加回来,请使用replace

关于python - 如何将字符串拆分为字符矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48407191/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com