Ho un frame di dati panda mydf
che ha due colonne e entrambe le colonne sono tipi di dati datetime: mydate
e mytime
. Voglio aggiungere altre tre colonne: hour
, weekday
e weeknum
.Aggiungere più colonne a Pandas Dataframe dalla funzione
def getH(t): #gives the hour
return t.hour
def getW(d): #gives the week number
return d.isocalendar()[1]
def getD(d): #gives the weekday
return d.weekday() # 0 for Monday, 6 for Sunday
mydf["hour"] = mydf.apply(lambda row:getH(row["mytime"]), axis=1)
mydf["weekday"] = mydf.apply(lambda row:getD(row["mydate"]), axis=1)
mydf["weeknum"] = mydf.apply(lambda row:getW(row["mydate"]), axis=1)
Il frammento funziona, ma non è computazionalmente efficiente come scorre il frame di dati almeno tre volte. Vorrei solo sapere se c'è un modo più veloce e/o più ottimale per farlo. Ad esempio, utilizzando zip
o merge
? Se, ad esempio, creo solo una funzione che restituisca tre elementi, come dovrei implementarla? Per illustrare la funzione sarebbe:
def getHWd(d,t):
return t.hour, d.isocalendar()[1], d.weekday()
Eventuali duplicati di [? E 'possibile aggiungere più colonne in una sola volta a un dataframe panda] (http : //stackoverflow.com/questions/19866377/is-it-possible-to-add-several-columns-at-once-to-a-pandas-dataframe) – geekazoid