如何在Pandas.jl DataFrame中实现日期列与索引日期相减并转为Float64
Hey there! No worries about formatting at all—first questions are all about getting the hang of things. Since you have Pandas experience, I’ll draw quick parallels where it makes sense, but let’s jump straight into the Julia solution you need.
First, let’s clean up your date parsing step (since looping through columns works, but we can make it more idiomatic Julia):
using DataFrames, Dates # Simplified date parsing function parse_date(date::String) = Date(date, Dates.DateFormat("d.mm.yyyy")) # Parse all columns in one go (instead of a loop) df = transform(df, names(df) .=> ByRow(parse_date) .=> names(df))
This is similar to using df.apply(pd.to_datetime) in Pandas—it applies the parsing function to every value in each column efficiently.
Next, let’s handle parsing your index axis dates and calculating the differences. First, we need to convert your string index to Date type:
# Convert row index strings to Date objects index_dates = parse_date.(rownames(df))
Now, to replace each column with the difference between its dates and the corresponding row index date (as a Float64 number of days):
# Calculate day differences and overwrite columns df = transform(df, names(df) .=> (col -> Float64.(col .- index_dates)) .=> names(df) )
Let me break that down:
col .- index_datescomputes element-wise date differences, giving us a vector ofDayobjectsFloat64.(...)converts eachDayto its numeric value (e.g.,Day(7)becomes7.0)- The
transformfunction applies this to every column and replaces the original columns with the results
If your "index axis" is actually a column in your DataFrame (instead of row names), the approach is even simpler. Let’s say your index date column is named row_date:
# Parse the index column first df[!, :row_date] = parse_date.(df[!, :row_date]) # Calculate differences for all other columns for col in setdiff(names(df), [:row_date]) df[!, col] = Float64.(df[!, col] .- df[!, :row_date]) end
This is analogous to df.sub(df['row_date'], axis=0) in Pandas—broadcasting the date subtraction across each column.
Hope this helps! Let me know if you run into any edge cases with date formats or DataFrame structure.
内容的提问来源于stack exchange,提问作者yasemento

