pandas 使其使用pd.concat

w8ntj3qf  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(103)

我想使用pd.concat,因为datetime64[ns]已被弃用。问题是我不知道如何使用。
代码如下:

ads_hour['Date'] = pd.to_datetime(ads_hour['Date'], errors='coerce')
ads['Time'] = pd.to_datetime(ads['Time'], errors='coerce')

merge_columns_ads_hour = "Date"
merge_columns_ads = "Time"

merged_ads_hour_ads = pd.merge(ads_hour, ads, left_on=merge_columns_ads_hour, right_on=merge_columns_ads)

merge_columns_advertising = "TV"

allData = pd.merge(merged_ads_hour_ads, advertising, left_on=merge_columns_ads, right_on=merge_columns_advertising)

# Display the first few rows of the merged DataFrame
print(allData.head())

字符串

n53p2ov0

n53p2ov01#

如果要使用pd.concat而不是pd.merge来合并基于日期时间列的 Dataframe ,则可以沿适当的轴沿着连接 Dataframe 。以下是更改代码的方法:

ads_hour['Date'] = pd.to_datetime(ads_hour['Date'], errors='coerce')
ads['Time'] = pd.to_datetime(ads['Time'], errors='coerce')

# Use pd.concat to merge based on datetime columns
merged_ads_hour_ads = pd.concat([ads_hour.set_index('Date'), ads.set_index('Time')], axis=1, join='inner')

# Reset the index to make 'Date' a column again
merged_ads_hour_ads.reset_index(inplace=True)

# Assuming 'Time' is in both DataFrames, you can now use pd.concat again
allData = pd.concat([merged_ads_hour_ads, advertising.set_index('TV')], axis=1, join='inner')

# Reset the index to make 'TV' a column again
allData.reset_index(inplace=True)

# Display the first few rows of the merged DataFrame
print(allData.head())

字符串
在这段代码中,set_index用于在连接之前将datetime列设置为索引,reset_index用于在连接之后将索引转换回列。join='inner'参数确保最终结果中仅包含具有匹配datetime值的行。

相关问题