You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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_dates computes element-wise date differences, giving us a vector of Day objects
  • Float64.(...) converts each Day to its numeric value (e.g., Day(7) becomes 7.0)
  • The transform function 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:17:48