从数据框中拆分和连接字符串

split & concat string from dataframe

来自数据框, 我想从 (col1) 第一个符号 | 之前的数字拆分为 a 列表,之后的第二个数字拆分为 b 列表和字符串 from(col1), (text1), ( text2), (text3) 进入 text 列表

col1       | text1     | text2           | text3
1|6|Show   | us the    | straight way    | null
109|2|I    | worship   | not that        | which ye worship

我预期的输出

a = [1, 109] b = [6, 2] text = [‘Show us the straight way’, ‘I worship not that which ye worship’]

最好的方法是什么?

这很简单,假设 col1 有 3 个管道分隔的元素。

a,b,C = zip(*df.col1.str.split('|'))
D =  df.drop('col1', 1).agg(lambda x: ' '.join(x.dropna()), axis=1)

c = [c + ' ' + d for c,d in zip(c,D)]

print(a)
('1', '109')

print(b)
('6', '2')

print(c)
['Show us the straight way', 'I worship not that which ye worship']

注意 ab 是字符串的集合,您可以使用

将它们映射为数字
a, b = map(pd.to_numeric, (a,b))

...获取整数数组。


要处理具有任意数量值的 col1 的一般情况,您需要

v = df.col1.str.split('|', expand=True)
m = v.applymap(str.isdigit)
a,b,*_ = v[m].T.agg(lambda x: x.dropna().tolist(), axis=1)

print(a)
['1', '109']

print(b)
['6', '2']

C可以类似计算:

C = v[~m].agg(lambda x: x.dropna().str.cat(sep=' '), axis=1).tolist()

然后小c可以像以前一样计算