首页 > 解决方案 > 使用 pandas str.split,其中出现需要是 pandas 列的值

问题描述

在弄清楚 pandas str.split 时遇到了一些麻烦。出现的地方来自列值,而不是为要拆分的字符串放置一个静态值。我环顾四周寻找类似类型的问题,但大多数似乎只是对拆分采用静态方法。

下面我有数据框。.str.split('|',1).str[-1] 将在第一次出现管道('|')时删除字符串的左侧部分。这种静态方法将在整个系列中执行相同的操作。因为发生参数没有改变。

我想要发生的事情: .str.split('|', df['occurrence'] ).str[-1] 可以是动态的,并利用发生列中的值并用作 str.split 发生争论。如果值为零或更小,则不对字符串执行任何操作。

lambda 语句实际上可以正常工作并正确执行,但是它从字符串的右侧开始,根据管道之间的值进行拆分和连接。但最后的结果是好的。不同的做法。我只是不能让它从字符串的左侧做同样的事情。

最后一点:删除需要从字符串的左侧开始。

#-------------------
import pandas as pd
from pandas import DataFrame, Series
import numpy as np

data_1 = {'occurrence': [7,2,0,3,4,0],
        'string': ['1|2|3|4|5|6|7|8|9|10|11|12','10|11.2|12.2|13.6|14.7','1|2|3',
                   '1|2|3|4|5|6|7|8','1|2.4|3|4.6|5|6.2|7|8.1','1|2|3|4|5'] }

df = pd.DataFrame(data_1)


df['string'] = df['string'].str.split('|',1).str[-1]  # Works but is static only

# df['string'] = df['string'].str.split('|',df['occurrence']).str[-1]  # Trying to use occurrence 
                                                                       # column value as argument

# Does work BUT starts with right side of string. Needs to be left.
# df['string'] = df.apply(lambda x: '|'.join(x['string'].split('|')[:x.occurrence - 2]), axis=1) 


print(df)
#-------------------

Start with:                                        What I would like:
occurrence   string                                occurrence    string   
7            1|2|3|4|5|6|7|8|9|10|11|12            7             8|9|10|11|12
2            10|11.2|12.2|13.6|14.7                2             12.2|13.6|14.7 
0            1|2|3                                 0             1|2|3 
3            1|2|3|4|5|6|7|8                       3             4|5|6|7|8 
4            1|2.4|3|4.6|5|6.2|7|8.1               4             5|6.2|7|8.1
0            1|2|3|4|5                             0             1|2|3|4|5

我会很感激你能在这个主题上发光,让我解决这个问题。一如既往,您的时间很宝贵,我感谢您。

标签: pythonpandasstringdataframesplit

解决方案


用于在 delimiter 周围Series.str.split拆分列,然后使用在列表理解内压缩拆分的列并处理值:string|zipoccurence

df['string'] = ['|'.join(s[i:]) for i, s in zip(df['occurrence'], df['string'].str.split('|'))]

结果:

print(df)
   occurrence          string
0           7    8|9|10|11|12
1           2  12.2|13.6|14.7
2           0           1|2|3
3           3       4|5|6|7|8
4           4     5|6.2|7|8.1
5           0       1|2|3|4|5

性能(使用 测量timeit):

df.shape
(60000, 2)

%%timeit -n10
_ = ['|'.join(s[i:]) for i, s in zip(df['occurrence'], df['string'].str.split('|'))]
67.9 ms ± 2.05 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit -n10 (using 'apply')
_ = df.apply(lambda x: '|'.join(x['string'].split('|')[x.occurrence:]), axis=1)
1.93 s ± 34.2 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

推荐阅读