我需要根據 2 個標準過濾 df:其中 Name != jack 并忽略 jack where Date <= 2020-04-01 的所有日期
# List of Tuples
df = [ ('jack', 'Apples' , '2020-01-01') ,
('Riti', 'Mangos' , '2020-02-01') ,
('Aadi', 'Grapes' , '2020-03-01') ,
('jack', 'Oranges', '2020-04-01') ,
('Lucy', 'Mangos' , '2020-05-01') ,
('jack', 'Apples' , '2020-12-01')
]
#Create a DataFrame object
df1 = pd.DataFrame(df, columns = ['Name' , 'Product', 'Date'])
df1
預期結果是:
Name Product Date
0 Riti Mangos 2020-02-01
1 Aadi Grapes 2020-03-01
2 Lucy Mangos 2020-05-01
3 jack Apples 2020-12-01
uj5u.com熱心網友回復:
boolean indexing多條件的
cond1 = df1['Name'] != 'jack'
cond2 = pd.to_datetime(df1['Date']) > pd.Timestamp('2020-04-01')
df1[cond1 | cond2].reset_index(drop=True)
輸出:
Name Product Date
0 Riti Mangos 2020-02-01
1 Aadi Grapes 2020-03-01
2 Lucy Mangos 2020-05-01
3 jack Apples 2020-12-01
uj5u.com熱心網友回復:
您可以執行以下操作:
import pandas as pd
# List of Tuples
df = [('jack', 'Apples' , '2020-01-01'),
('Riti', 'Mangos' , '2020-02-01'),
('Aadi', 'Grapes' , '2020-03-01'),
('jack', 'Oranges', '2020-04-01'),
('Lucy', 'Mangos' , '2020-05-01'),
('jack', 'Apples' , '2020-12-01')
]
#Create a DataFrame object
df1 = pd.DataFrame(df, columns = ['Name', 'Product', 'Date'])
# Filtering for condition Name = !jack
df1 = df1[df1['Name'] != 'jack']
# Convert the date to datetime64
df1['Date'] = pd.to_datetime(df1['Date'], format='%Y-%m-%d')
# Filter by specified date
filtered_df = df1.loc[(df1['Date'] <= '2020-04-01')]
# print the filtered result
print(filtered_df)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/530838.html
標籤:Python熊猫麻木的
上一篇:繪制內核嶺回歸會導致奇怪的線條
