遍历数据框中的特定列并返回true或false(即,如果我的文本中有一个数字)

时间:2019-03-25 11:13:16

标签: pandas dataframe

df = pd.DataFrame({text_summary: ['my students need 8\ tablets to work on a project', 'My students need 5 tablets for our classroom technology center PLEASE!!!']

我想遍历text_summary列的每一行,并检查是否有数字,并返回true或false,然后在同一数据框中使用返回的值创建另一列。

1 个答案:

答案 0 :(得分:0)

首先由正则表达式from django import forms from .models import Contract from bootstrap_modal_forms.mixins import PopRequestMixin, CreateUpdateAjaxMixin class ContractForm(PopRequestMixin, CreateUpdateAjaxMixin, forms.ModelForm): class Meta: model = Contract fields = ('organisatie','tussenpersoon','tussenpersoon_email',) 生成的Series.str.extract数字,然后由Series.str.isdigit测试:

\d+

另一个想法是使用Series.str.contains

df = pd.DataFrame({'text_summary': ['my students need 8\ tablets to work on a project', 
                                    'My students need 5 tablets for 
                                     our classroom technology center PLEASE!!!',
                                    'no digit']})

df['digit'] = df['text_summary'].str.extract('(\d+)', expand=False)
df['test'] = df['digit'].str.isdigit().fillna(False)
print (df)

                                        text_summary digit   test
0   my students need 8\ tablets to work on a project     8   True
1  My students need 5 tablets for our classroom t...     5   True
2                                           no digit   NaN  False