求助:基于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 topd.to_datetimeand it creates proper datetime objects. - For
data2.csv, pandas'to_datetimecan automatically recognize full month names (like "January"), so we don't need that bulkyget_monthfunction at all!
- For
- Combining data:
pd.concatmerges the two datasets in one line, keeping only the columns we care about (DateandTweet). - Sorting: A single
sort_valuescall handles the date sorting—way simpler than writing a custom loop with counters. - Date formatting: Using
dt.strftimedirectly on the datetime column lets us format dates in the required%d-%b-%ypattern 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
相关产品推荐
相关产品推荐

