在Python中查找前导为零的记录

2024-06-16 09:42:43 发布

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

例如,我有一个dataframe,如下所示

df1 = pd.DataFrame({'Acct_no':['010122','002291','110082','000090'],
                    'Int_rate':[2, 3, 2, 2],
                    'US_GDP_Thousands':[50, 55, 65, 55]},
                   index = [21,2, 3, 20])

上面的代码生成以下数据帧

   Acct_no  Int_rate  US_GDP_Thousands
21  010122         2                50
2   002291         3                55
3   110082         2                65
20  000090         2                55

如何找到帐户编号以零开头的所有列值。你知道吗

所以,我想从上面的数据帧得到以下结果。我需要运行什么代码?你知道吗

   Acct_no  Int_rate  US_GDP_Thousands
21  010122         2                50
2   002291         3                55
20  000090         2                55

Tags: 数据nodataframeindexrate帐户代码生成int
3条回答

另一种解决方案:

df1[df1.Acct_no.str.match(r'0.*')]

使用startswith

df1.loc[df1.Acct_no.str.startswith('0')]
Out[182]: 
   Acct_no  Int_rate  US_GDP_Thousands
21  010122         2                50
2   002291         3                55
20  000090         2                55

这应该起作用:

df1[df1['Acct_no'].str[0] == '0']

相关问题 更多 >