For Loop 和 Series 的真值不明确
For Loop and The truth value of a Series is ambiguous
在这里查看了类似查询的答案,但仍然不确定。下面的代码产生:
for i in range(len(df)):
if df[0]['SubconPartNumber1'].str.isdigit() == False :
df['SubconPartNumber1'] = df['SubconPartNumber1'].str.replace(',', '/', regex = True)
df['SubconPartNumber1'] = df['SubconPartNumber1'].str.replace(r"\(.*\)-", '/', regex = True)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
在 pandas 你可以 avoid loops if possible. Your solution should be replace by boolean mask
with ~
for invert instead == False
and passed to DataFrame.loc
:
m = df['SubconPartNumber1'].str.isdigit()
df.loc[~m, 'SubconPartNumber1'] = df.loc[~m, 'SubconPartNumber1'].str.replace(',', '/', regex = True).str.replace(r"\(.*\)-", '/', regex = True)
但是因为numeric只有数字我认为这里不需要掩码,对于or
也应该用|
加入正则表达式,regex=True
是默认参数,所以应该省略:
df = pd.DataFrame({'SubconPartNumber1':['345','aaa,','(bbb)-ccc']})
print (df)
SubconPartNumber1
0 345
1 aaa,
2 (bbb)-ccc
df['SubconPartNumber1'] = df['SubconPartNumber1'].str.replace(r",|\(.*\)-", '/')
print (df)
SubconPartNumber1
0 345
1 aaa/
2 /ccc
替换为:
if df[0]['SubconPartNumber1'].str.isdigit() == False :
有了这个:
if df[0]['SubconPartNumber1'].str.isdigit().empty:
除了 empty
之外还有其他方法,但我认为这会满足您的需求。
在这里查看了类似查询的答案,但仍然不确定。下面的代码产生:
for i in range(len(df)):
if df[0]['SubconPartNumber1'].str.isdigit() == False :
df['SubconPartNumber1'] = df['SubconPartNumber1'].str.replace(',', '/', regex = True)
df['SubconPartNumber1'] = df['SubconPartNumber1'].str.replace(r"\(.*\)-", '/', regex = True)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
在 pandas 你可以 avoid loops if possible. Your solution should be replace by boolean mask
with ~
for invert instead == False
and passed to DataFrame.loc
:
m = df['SubconPartNumber1'].str.isdigit()
df.loc[~m, 'SubconPartNumber1'] = df.loc[~m, 'SubconPartNumber1'].str.replace(',', '/', regex = True).str.replace(r"\(.*\)-", '/', regex = True)
但是因为numeric只有数字我认为这里不需要掩码,对于or
也应该用|
加入正则表达式,regex=True
是默认参数,所以应该省略:
df = pd.DataFrame({'SubconPartNumber1':['345','aaa,','(bbb)-ccc']})
print (df)
SubconPartNumber1
0 345
1 aaa,
2 (bbb)-ccc
df['SubconPartNumber1'] = df['SubconPartNumber1'].str.replace(r",|\(.*\)-", '/')
print (df)
SubconPartNumber1
0 345
1 aaa/
2 /ccc
替换为:
if df[0]['SubconPartNumber1'].str.isdigit() == False :
有了这个:
if df[0]['SubconPartNumber1'].str.isdigit().empty:
除了 empty
之外还有其他方法,但我认为这会满足您的需求。