带有拆分字符串的dataframe.loc

2024-10-01 11:24:15 发布

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

如何使用split匹配列中转换为str的int

personid = '23'
cond = (personid == x for x in df['wait'].str.split(","))
rows = df.loc[cond, :]

df['wait']包含类似“2,13,23”的str

当前它返回Empty DataFrame


Tags: indataframedfforlocemptyrowsint
1条回答
网友
1楼 · 发布于 2024-10-01 11:24:15

如果将expand=True添加到^{}获取数据帧,并通过拆分的值使用新列fileld,然后通过==by ^{}进行比较,并通过^{}测试每行是否至少有一个True。由^{}进行的最后筛选:

#personid is string - `''`
personid = '23'
cond = df['wait'].str.split(",", expand=True).eq(personid).any(axis=1)

rows = df[cond]

如果要匹配personid中的整数值:

#personid is integer
personid = 23
cond = df['wait'].str.split(",", expand=True).astype(float).eq(personid).any(axis=1)

rows = df[cond]

您的解决方案应该更改:

cond  = [any(y == personid for y in x) for x in df['wait'].str.split(",")]

相关问题 更多 >