在 Pandas 1.3.4 和 Python 3.9 上。
所以我在過濾部分字串時遇到了問題。“日期”列以 MM/DD/YYYY HH:MM:SS A/PM 格式列出,其中最近的列在頂部。如果日期是個位數(例如:11 月 3 日),則它沒有 0,因此它是 11/3 而不是 11/03。基本上,我希望查看名為“Date”的列,并讓 python 讀取部分字串以僅在今天進行過濾。
這就是原始 csv 的樣子。這就是我想要對檔案做的事情。基本上尋找特定日期而不是該日期的任何時間并實作 =RIGHT() 公式。然而,這就是我最終得到以下代碼的結果。
from datetime import date
import pandas as pd
df = pd.read_csv(r'file.csv', dtype=str)
today = date.today()
d1 = today.strftime("%m/%#d/%Y") # to find out what today is
df = pd.DataFrame(df, columns=['New Phone', 'Phone number', 'Date'])
df['New Phone'] = df['Phone number'].str[-10:]
df_today = df['Date'].str.contains(f'{d1}',case=False, na=False)
df_today.to_csv(r'file.csv', index=False)
uj5u.com熱心網友回復:
這一行是錯誤的:
df_today = df['Date'].str.contains(f'{d1}',case=False, na=False)
你所做的就是創建一個面具;本質上,這只是一個 Pandas 系列,包含True或False在每一行中,根據您創建掩碼的條件。電子表格僅FALSE如您所示,因為其中沒有Date包含變數所包含的字串的專案d1...
相反,試試這個:
from datetime import date
import pandas as pd
# Load the CSV file, and change around the columns
df = pd.DataFrame(pd.read_csv(r'file.csv', dtype=str), columns=['New Phone', 'Phone number', 'Date'])
# Take the last ten chars of each phone number
df['New Phone'] = df['Phone number'].str[-10:]
# Convert each date string to a pd.Timestamp, removing the time
df['Date'] = pd.to_datetime(df['Date'].str.split(r'\s ', n=1).str[0])
# Get the phone numbers that are from today
df_today = df[df['Date'] == date.today().strftime('%m/%d/%Y')]
# Write the result to the CSV file
df_today.to_csv(r'file.csv', index=False)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/353847.html
上一篇:for回圈中的條件不明確
