[英]How to add a new column to a pandas dataframe while calculate the elements?
我想向pandas df添加一個新列,該列將基於另一列進行計算。 這是df的簡述:
如果日期在start_date1
和end_date1
之間,則應在期間列“ 0”中輸出。 如果日期在start_date2
和end_date2
之間,則輸出“ 1”,依此類推。
有沒有辦法做到這一點而沒有循環?
謝謝你的幫助 :)
拉里
首先,您需要檢查列date
是否具有datetime
格式。
您可以使用df.dtypes
進行檢查。 如果它沒有日期格式( datetime64
),則必須使用以下命令將其轉換為datetime:
df['date'] = pd.to_datetime(df.date, format='%Y%m%d', errors='ignore')
請注意,參數errors='ignore'
具有風險,因此是可選參數。
現在,要計算字段,您可以執行以下操作:
# define function to calculate periods based on date
def calculate_period(row):
if row['date'] > start_date1 & row['date'] < end_date1:
return "0"
elif row['date'] > start_date2 & row['date'] < end_date2:
return "1"
elif row['date'] > start_date3 & row['date'] < end_date3:
return "2"
else:
return "unknown"
# apply function to create the new column
df['period'] = df.apply(calculate_period, axis=1)
如果需要更多的period
值,則可以根據需要擴展elif
語句。
由於缺少有關您的數據的信息。 我假設start_date1
和end_date1
是您定義的變量。
如果這些也是列。 該函數將如下所示:
# define function to calculate periods based on date
def calculate_period(row):
if row['date'] > row['start_date1'] & row['date'] < row['end_date1']:
return "0"
elif row['date'] > row['start_date2'] & row['date'] < row['end_date2']:
return "1"
elif row['date'] > row['start_date3'] & row['date'] < row['end_date3']:
return "2"
else:
return "unknown"
# apply function to create the new column
df['period'] = df.apply(calculate_period, axis=1)
祝好運。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.