Python 寻找一个与panda中的整数等价的starts
我有一个整数列。所有行都有9位数字,第一行以5或7开头。我正在尝试筛选那些只以7开头的。整数数据类型是否有一个等效的.str.startswith?或者我需要转换为字符串并返回整数吗Python 寻找一个与panda中的整数等价的starts,python,pandas,Python,Pandas,我有一个整数列。所有行都有9位数字,第一行以5或7开头。我正在尝试筛选那些只以7开头的。整数数据类型是否有一个等效的.str.startswith?或者我需要转换为字符串并返回整数吗 df["Case #"].str.startswith(7) 如果它们都是9位数字,您可以使用数字比较: (df[“Case#”]。介于(70000000、79999999)之间 |df[“案例#”]。介于(500000000、59999999)之间 只需执行以下操作: df = df[(df["Case #"]
df["Case #"].str.startswith(7)
如果它们都是9位数字,您可以使用数字比较:
(df[“Case#”]。介于(70000000、79999999)之间
|df[“案例#”]。介于(500000000、59999999)之间
只需执行以下操作:
df = df[(df["Case #"].astype(str).str.startswith('7')) | (df["Case #"].astype(str).str.startswith('5'))]
或
这里有很多剥猫皮的方法:
# fake
np.random.seed([3, 14])
s = pd.Series((np.random.choice(8, 10) + 1) * 1e8, name='Case', dtype='int')
s
0 100000000
1 800000000
2 500000000
3 200000000
4 800000000
5 500000000
6 400000000
7 500000000
8 600000000
9 700000000
Name: Case, dtype: int64
由于所有数字都有相同的数字,因此使用算术与isin检查:
# (df['case'] // 1e8).astype(int).isin([5, 7])
(s // 1e8).astype(int).isin([5, 7])
0 False
1 False
2 True
3 False
4 False
5 True
6 False
7 True
8 False
9 True
Name: Case, dtype: bool
这要慢得多。转换为字符串并检查第一个数字
# Here, comparison is with strings, not integers.
s.astype(str).str[0].isin(['5', '7'])
0 False
1 False
2 True
3 False
4 False
5 True
6 False
7 True
8 False
9 True
Name: Case, dtype: bool
提醒:更多、更多、更慢。如果您关心这样的格式,它可能首先不应该是一个数字。更新为一次比较多个值。谢谢,我对isin还不太熟悉。。我们将在中回顾此方法future@msulol你现在能复习一下吗?我打赌这比字符串比较好。当然,我尝试了第一行代码,但我无法将其过滤,我还不能完全理解语法。这是我试过的,我想我100%错了。(df[“Case#”]//1e9.astype(int).isin([5,7])@msulol您说的是9位数字,也许您需要
(df[“Case#”]//1e8.astype(int).isin([5,7])
而不是1e9
“对熊猫不起作用,因为您在向量上应用条件,您需要将
包装在括号内。另外,(aseries.between(a,b,inclusive=True)
,以避免同样的问题。@cs95我不是pandas程序员——如果您可以编辑答案以显示正确的语法,那就太好了。或者你可以发布一个正确的答案,我将删除。已修复,但我非常喜欢坚持算术检查的想法,因为字符串运算通常比使用pandas的算术运算慢。@cs95但我仍然认为它们可能不应该使用数字。这就像使用信用卡号码、电话号码、账号、邮政编码等。即使它们包含数字,但它们也不是真正的数字。是的,我也不建议这样做,尤其是当涉及丢失数据时。在pandas>=1.0上,虽然NA值与INT具有更好的互操作性,因此没有什么大不了的,但由于使用数字运算可能会获得性能提升,因此可能会首选NA值。如果OP想像问题所描述的那样添加对5的检查,则需要df[df[“Case#”].astype(str).str.startswith('7')| df[“Case#”].astype(str).str.startswith('5')]
不用担心,现在看起来是正确的,尽管您可能应该考虑掉冗余的df[“Case#”].astype(str)
计算(如果您愿意)。由于它是一个整数列,所以需要它是的,但您只需要做一次,就要做两次,如果这有意义的话。这起作用了,我不知道你可以用这种方式来连锁。谢谢df=df[df[“Case#”].astype(str).str.contains(r'^7')]
# Here, comparison is with strings, not integers.
s.astype(str).str[0].isin(['5', '7'])
0 False
1 False
2 True
3 False
4 False
5 True
6 False
7 True
8 False
9 True
Name: Case, dtype: bool