![](/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.