![](/img/trans.png)
[英]In a pandas dataframe, how can I filter the rows based on a column value, do calculation and assign the result to a new column?
[英]How do I can filter pandas DataFrame by slice of column value
假设我有以下数据框:
ter_id shstr value
6 2018002000000 201 1740.0
7 2018002000000 201 10759.0
8 2018002000002 201 2.0
如何过滤掉ter_id
最后六个符号为零的行? 这是期望的输出是:
ter_id shstr value
8 2018002000002 201 2.0
我做了一个布尔函数
def is_total(ter_id: str) -> bool:
if ter_id[:-6] == "000000":
return True
return False
但它使用失败并出现错误:
dataset.filter(is_total(dataset.ter_id))
...
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
熊猫版本是 1.0.1
通过[-6:]
更改最后6
值的索引并通过boolean indexing
获取所有不匹配的行:
df = dataset[dataset.ter_id.str[-6:] != "000000"]
print (df)
ter_id shstr value
8 2018002000002 201 2.0
为了根据列值过滤数据框,很少有理由编写自己的函数。 您可以将条件作为布尔掩码传递到 df.loc[](假设您的 DataFrame 名为 df)。
df = df.loc[df["ter_id"].str[-6:] != "000000"]
国际大学联盟
df[~(df.ter_id%1000000==0)]
Out[256]:
ter_id shstr value
8 2018002000002 201 2.0
好吧,我想到的是您应该首先将列 (ter_id) 转换为字符串。 然后在整个列上使用 .contains 方法
df_filtered = df[~df.ter_id.str.contains("000000")].copy()
df
是您的数据框名称。 我使用copy()
函数来抑制警告。 让我知道这是否有帮助....
PS 您可以输入任何字符串而不是零。
不需要 Python 函数,你可以使用:
dataset[dataset['ter_id'].str.slice(-6) != '000000']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.