在python或R中,我想要一种更有效的方法将一列中的文本拆分为四列

2024-09-27 00:21:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为BREADS的列,有5行,我想将该列和值拆分为4列,即BREADS


BREADS
>2319-22-<21
>1513-16-<19
>1319-25-<22
>1617-21-<25
>1011-15-<17

预期结果


B, REA , D, S    ### column names
>23 , 19-22 , - , <21
>15 , 13-16 , - , <19
>13 , 19-25 , - , <22
>16 , 17-21 , - , <25
>10 , 11-15 , - , <17

# Key: > greater than and < less than, - hyphen in the column 'D'

我的尝试

###### in python
# for column 'B'
df['B'] = df['BREADS'].astype(str).str[0:4]   # returns '>23','>15',.....,'>10'


#### in R 

library(stringr)
str_split_fixed(df$BREADS, "", 2)


Tags: andthekeyindfnamescolumnless
3条回答

您可以使用pandas str.extract将数据拉入单独的列中;这里的假设是每一行的数据是一致的:

pattern = r"(?P<B>>.{2})(?P<REA>.{2}-.{2})(?P<D>-)(?P<S><.{2})"

df.BREADS.str.extract(pattern)

      B  REA    D    S
0   >23 19-22   -   <21
1   >15 13-16   -   <19
2   >13 19-25   -   <22
3   >16 17-21   -   <25
4   >10 11-15   -   <17

R中带有extractfrom tidyr的选项

library(dplyr)
library(tidyr)
df1 %>% 
 extract(BREADS, into = c('B', 'REA', 'D', 'S'),
        '^(\\>..)(\\d{2}-\\d{2})(-)(.*)')

-输出

#  B   REA D   S
#1 >23 19-22 - <21
#2 >15 13-16 - <19
#3 >13 19-25 - <22
#4 >16 17-21 - <25
#5 >10 11-15 - <17

数据

df1 <- structure(list(BREADS = c(">2319-22-<21", ">1513-16-<19", ">1319-25-<22", 
">1617-21-<25", ">1011-15-<17")), class = "data.frame", row.names = c(NA, 
-5L))

对于Python:

d={'B': (0,4), 'REA':(3,8), 'D':(8,9), 'S':(9:20)}
for i in d:
    df[i]=df['BREADS'].apply(lambda x: x[d[i][0]:d[i][1])

相关问题 更多 >

    热门问题