假设我有一个数据集,其头如下所示
https://gist.github.com/ahmadmustafaanis/9ba3b5ea25b46b2b87ab858dc57ec15d
现在我想检查一下df' link‘中的链接是否包含'edx’或'coursera‘,那么name也应该包含它。
首先,我必须看到所有的链接,其中包含'edx‘或’Cour何时‘。我的逻辑是
df['Link'][df['Link'].isnull()==False].apply(lambda a: True if 'coursera' in a else True if 'edx' in a else False)
它返回一个真和假的布尔序列,用于它们中包含Coursera或Edx的链接。
现在,如果我想通过在dfmycode或df.locmycode中封装这段代码来访问整个数据帧,它会给出错误和警告。
df[df['Link'][df['Link'].isnull()==False].apply(lambda a: True if 'coursera' in a else True if 'edx' in a else False)]
警告是
<ipython-input-47-d903df486dc7>:1: UserWarning: Boolean Series key will be reindexed to match DataFrame index.
df[df['Link'][df['Link'].isnull()==False].apply(lambda a: True if 'coursera' in a else True if 'edx' in a else False)]
错误信息是
IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match).
发布于 2020-08-26 01:16:12
你的代码行对我来说都没有失败。似乎是一个非常复杂的方式,能够过滤一个数据。只需为想要的行定义一个具有True
的掩码,然后使用loc[mask]
import requests
res = requests.get("https://gist.githubusercontent.com/ahmadmustafaanis/9ba3b5ea25b46b2b87ab858dc57ec15d/raw/53c5f357f2e9db0d37e420a9b18a60ac7a8bdfa6/test.csv")
df = pd.read_csv(io.StringIO(res.content.decode()))
df['Link'][df['Link'].isnull()==False].apply(lambda a: True if 'coursera' in a else True if 'edx' in a else False)
df[df['Link'][df['Link'].isnull()==False].apply(lambda a: True if 'coursera' in a else True if 'edx' in a else False)]
mask = df["Link"].str.contains("coursera") | df["Link"].str.contains("edx")
df.loc[mask]
https://stackoverflow.com/questions/63593556
复制相似问题