我需要选择“栏分隔符”之前的字符串列的一部分
“ Str”列包含:['AA|B','BB|CCC','D|LLL']
我已经创建了另一个名为“ | index”的列 该列返回索引号“ |”分隔符
,我想返回一个新的列,该列仅在“ |”之前包含子字符串使用'.apply()'方法:
def substring (x):
return x[1].str.slice(0,x[2])
df['new']=df.apply(substring,axis=1)
但是,这根本不起作用!!!! 我想知道为什么
df = pd.DataFrame({'Num':list(range(0,26,5)),'Str':'AA|B BB|CCC D|LLL EEE|easy f|failed g|Gg'.split()})
df["| index"] = df['Str'].str.find("|")
df
def substring (x):
return x[1].str.slice(0,x[2])
df['new']=df.apply(substring,axis=1)
答案 0 :(得分:1)
0
0 [AA|B, BB|CCC, D|LLL]
df = pd.DataFrame(df[0].tolist()).unstack().reset_index(drop=True)
##df
0 AA|B
1 BB|CCC
2 D|LLL
dtype: object
pd.DataFrame(df.apply(lambda x: [x.find('|'),x[:x.find('|')]]).tolist()).rename({0:'Bar Position',1:'Substring'},axis=1)
Bar Position Substring
0 2 AA
1 2 BB
2 1 D