抓取某个值之后的字符

2024-09-29 01:29:07 发布

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

下面是数据帧。picu 1和Wgt是字符串,p.lgth和p\u lgth是整数。如果p\u lgth不等于30,我想在PIC\u 1中找到42,然后抓取42和它后面的15个数字。你知道吗

                                            PIC_1  Wgt  p.lgth  p_lgth
**PARTIAL-DECODE***P / 42011721930018984390078...  112      53      53

所以上面的输出应该是42011721930018984

我的代码如下:

def pic_mod(row):
 if row['p_lgth'] !=30:
    PIC_loc = row['PIC_1'].find('42')
    PIC_2 = row['PIC_1'].str[PIC_loc:PIC_loc + 15]
 elif row['p_lgth']==30:
    PIC_2=PIC_1  
 return PIC_2

第1行只是较大df中的一行,与上面给出的示例行相同

 row_1 = df71[2:3]
 pic_mod(row_1)

 ValueError: The truth value of a Series is ambiguous. Use a.empty, 
 a.bool (), a.item(), a.any() or a.all().

我在变量上做了type(),得到了

  type(df71['PIC_1']) = pandas.core.series.Series
  type(df71['p_lgth']) = pandas.core.series.Series
  type(df71['Wgt']) = pandas.core.series.Series

我对Python还比较陌生。这些数据类型应该返回int和str吗?df71是一个df。你知道吗


Tags: coremodpandasdftypelocrowseries
1条回答
网友
1楼 · 发布于 2024-09-29 01:29:07

根据你帖子中的错误信息,不妨尝试一下:

def pic_mod(row):
 if row['p_lgth'].any() != 30:
    PIC_loc = row['PIC_1'].str.find('42')[0]
    PIC_2 = row['PIC_1'].str[PIC_loc:PIC_loc + 17]
 elif row['p_lgth'].any() == 30:
     PIC_2=PIC_1  
 return PIC_2

但是,如果您的数据已经在数据帧中结构化,则通常不会编写这样的显式函数。你知道吗

例如,按长度不等于30对数据集中所有行进行的初始筛选将是一行,如:

df_fltrd = df[df['p_lgth']!=30]

完成此操作后,您可以对PIC_1-列中的条目应用任意函数,例如,在您的示例中,长度为17、以“42”开头的子字符串:

df_fltrd['PIC_1'].apply(lambda x: x[x.find('42'):x.find('42')+17])

相关问题 更多 >