【问题标题】:statement based on whether string field starts with number基于字符串字段是否以数字开头的语句
【发布时间】:2019-03-23 14:20:27
【问题描述】:

我有一个带有两个街道地址列的 pandas 数据框。我想检查每一列中的值,看看它是否以数字开头。然后我想创建第三列,它返回以数字开头的字段值。

考虑以下df:

df = pd.DataFrame({"A":["123 Fake St","456 Fake St","Crown Building","Other Building"], 
                   "B":["Dorm","12 Dorm","34 Dorm","Other Dorm"]})

如果两个字段或两个字段都不是以数字开头,那么它应该返回 A 列。所以第三列是:

123 Fake St
456 Fake St
34 Dorm
Other Building

我尝试使用 np.where:

df['C'] = np.where(df['A'][0].isdigit(), df['A'], df['B'])

我猜如果两者都不以数字开头,则不考虑返回“A”。声明的 .isdigit 部分似乎无论如何都不起作用。

感谢您的帮助!

【问题讨论】:

标签: python python-3.x pandas if-statement


【解决方案1】:

您需要使用.str 方法将每个单元格值切片为一个字符串,而不是将列作为一个整体切片。

那么要处理两个列的值都不是以数字开头的情况,你需要添加这个附加条件。

这是一个例子:

a_is_digit = df.A.str[0].str.isdigit()
neither_is_digit = ~df.A.str[0].str.isdigit() & ~df.B.str[0].str.isdigit()
mask = a_is_digit | neither_is_digit
df['C'] = np.where(mask, df.A, df.B)

结果:

                A           B               C
0     123 Fake St        Dorm     123 Fake St
1     456 Fake St     12 Dorm     456 Fake St
2  Crown Building     34 Dorm         34 Dorm
3  Other Building  Other Dorm  Other Building

【讨论】:

  • 谢谢!稍作修改后,最后一行是: df['C'] = np.where(mask, df['A'], df['B'])
猜你喜欢
  • 2023-01-01
  • 2014-01-15
  • 1970-01-01
  • 1970-01-01
  • 2011-05-04
  • 1970-01-01
  • 1970-01-01
  • 2016-05-02
  • 2011-07-31
相关资源
最近更新 更多