Python 3.x 在.str.find()中使用if语句
我想知道我是否有这样的If语句:Python 3.x 在.str.find()中使用if语句,python-3.x,pandas,if-statement,Python 3.x,Pandas,If Statement,我想知道我是否有这样的If语句: if int(i) > 10: return 0 else: return -1 其中,i相当于df[“price”](df是数据帧)中的行条目,定义如下: import pandas as pd df = pd.DataFrame(columns=["price", "Number"], data=[["10", "07367"], ["20", "08356"], ["9", "07745"]]) 如何将df[“price”].st
if int(i) > 10:
return 0
else:
return -1
其中,i
相当于df[“price”]
(df是数据帧)中的行条目,定义如下:
import pandas as pd
df = pd.DataFrame(columns=["price", "Number"], data=[["10", "07367"], ["20", "08356"], ["9", "07745"]])
如何将df[“price”].str.find(…)
与上述if语句一起使用,根据真实条件过滤数据
我希望输出如下所示:
0 -1
1 0
2 -1
我一直在努力解决如何实现它,请协助。您可以使用+:
输出
0 -1
1 0
2 -1
Name: price, dtype: int64
[-1 0 -1]
或者,如果您愿意,您可以使用@coldspeed在评论中提到的
import numpy as np
import pandas as pd
df = pd.DataFrame(columns=["price", "Number"], data=[["10", "07367"], ["20", "08356"], ["9", "07745"]])
result = np.where(df.price.astype(int) > 10, 0, -1)
print(result)
输出
0 -1
1 0
2 -1
Name: price, dtype: int64
[-1 0 -1]
只需使用lambda函数即可
df.price.apply(lambda x : 0 if int(x)>10 else -1)
您可以使用:
语法是:
np.where(condition,valueIfTrue,valueIfFalse)
通常最容易首先转换为最佳的数据类型。这样所有操作都会更快——当然,这取决于您的应用程序是否重要。但如果事情是数字,就让它们成为数字(显式>隐式)
然后可以将条件添加为列(或仅使用输出)。Apply或map并不是那么快,所以最好使用别人建议的np.where
,或者任何其他将在引擎盖下使用numpy的比较。例如:
df['criteria'] = -1 * (df.price <= 10).astype(int) # quicker to not use map or apply
df.criteria
df['criteria']=-1*(df.price您可以添加一些数据样本吗?抱歉,我已经添加了一些样本数据。预期的输出是什么?为什么要使用str.find
?我想您可以使用np.where(df.price.astype(int)>10,0,-1)
很好的解决方案:)
df['criteria'] = -1 * (df.price <= 10).astype(int) # quicker to not use map or apply
df.criteria