通过拆分可选的前导非字符串字符来计算新列

2024-06-08 01:18:45 发布

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

我是Pandas的新手,正在尝试添加两个新列,其中的值是从现有的“Result”列计算出来的

现有列包括带有可选限定符(“<;”、”的数字>;','<>;'))

“结果”中的一些样本编号可能是:

0.5
12.67
3
<1
4.5
>10.0

我想要一个新的“Result_Q”列,其中包含非数值限定符(如果存在),否则为NULL(None),以及一个新的“Result_Value”列,其中包含数值组件

我的第一次尝试失败是:

df['Result_Q'] = df.Result.str[0] if not df.Result.str[0].isdigit() else None

这会产生错误AttributeError: 'Series' object has no attribute 'isdigit'

(在研究了这个错误之后,我尝试了其他一些产生错误的变体 ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()


Tags: ltgtnonepandasdf错误数字result
3条回答

或者尝试:

df['Result_Q'] = df['Result'].str.replace('\d+', '').str.strip('.').replace('', np.nan)
print(df)

输出:

  Result Result_Q
0    0.5      NaN
1  12.67      NaN
2      3      NaN
3     <1        <
4    4.5      NaN
5  >10.0        >

您可以使用df.apply创建新列:

import pandas as pd
df = pd.DataFrame({'result': ['0.5', '12.67', '<1', '4.5', '>10.0']})
df['Result_Q'] = df['result'].apply(lambda x: x[0] if not x[0].isdigit() else None)
print(df)


  result Result_Q
0    0.5     None
1  12.67     None
2     <1        <
3    4.5     None
4  >10.0        >

^{}^{}一起使用:

df['Result_Q'] = np.where(df.Result.str[0].str.isdigit(), None, df.Result.str[0])

替换为^{}

df['Result_Q'] = df.Result.str[0].mask(df.Result.str[0].str.isdigit(), None)

print (df)
  Result Result_Q
0    0.5     None
1  12.67     None
2      3     None
3     <1        <
4    4.5     None
5  >10.0        >

^{}NaN更改为None

df['Result_Q'] = df.Result.str[0].str.extract('(\D)').mask(lambda x: x.isna(), None)
print (df)
  Result Result_Q
0    0.5     None
1  12.67     None
2      3     None
3     <1        <
4    4.5     None
5  >10.0        >

相关问题 更多 >

    热门问题