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

求助:基于Pandas合并两表生成日期排序新表的简化实现方案

Hey there! Let's simplify this with pandas' built-in functions—no need for all those loops and custom date conversion functions. Here's a concise, clean solution that gets the job done in way fewer lines:

import pandas as pd

# Load both CSV files
df1 = pd.read_csv("data1.csv")
df2 = pd.read_csv("data2.csv")

# Create unified Date column for df1 (Month is numeric)
df1["Date"] = pd.to_datetime(df1[["Year", "Month", "Day"]])

# Create Date column for df2 (Month is full name, pd.to_datetime handles it automatically)
df2["Date"] = pd.to_datetime(df2[["Year", "Month", "Day"]])

# Keep only the columns we need and combine the two DataFrames
combined_df = pd.concat(
    [df1[["Date", "Tweet"]], df2[["Date", "Tweet"]]],
    ignore_index=True
)

# Sort by date (add ascending=False for descending order)
sorted_df = combined_df.sort_values("Date")

# Format date to the required dd-Mon-yy format
sorted_df["Date"] = sorted_df["Date"].dt.strftime("%d-%b-%y")

# Print the final result
print(sorted_df)

Breakdown of what's happening here:

  • Reading data: Pandas handles the CSV parsing natively, no need to manually convert columns to lists or reverse them.
  • Date parsing:
    • For data1.csv, since the Month column is numeric, we just pass the Year/Month/Day columns to pd.to_datetime and it creates proper datetime objects.
    • For data2.csv, pandas' to_datetime can automatically recognize full month names (like "January"), so we don't need that bulky get_month function at all!
  • Combining data: pd.concat merges the two datasets in one line, keeping only the columns we care about (Date and Tweet).
  • Sorting: A single sort_values call handles the date sorting—way simpler than writing a custom loop with counters.
  • Date formatting: Using dt.strftime directly on the datetime column lets us format dates in the required %d-%b-%y pattern without a separate function.

If you want the dates sorted in descending order instead, just modify the sort line to:

sorted_df = combined_df.sort_values("Date", ascending=False)

内容的提问来源于stack exchange,提问作者clumbzy1

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:23:40