datetime64类型为映射值的Pandas map()函数

2024-09-27 21:34:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图从dict weather向我的数据帧data添加一个新列Temperature。使用map()函数将data中的日期与weather中的日期进行匹配,两者都是datetime64格式。你知道吗

import pandas as pd

# Import first dataset and convert dates to datetime64
filename = 'Process Data.csv'
data = pd.read_csv(filename)
data['trans_date1'] = pd.to_datetime(data.trans_date1)

# Import second dataset and convert dates to datetime64
filenameWeather = '2014-2018 Weather Data.csv'
dataWeather = pd.read_csv(filenameWeather, parse_dates=True)
dataWeather['Date_Time'] = pd.to_datetime(dataWeather.Date_Time)


# Create new dataframe to hold only the date and temp 
weather = dataWeather[[('Date_Time'), 'Mean_Temp_?C']].copy()

# Convert this to a dict
weather = weather.to_dict('split')

# map weather data to main dataset
data['Temperature'] = data['trans_date1'].map(weather)

这不会产生错误,但不会复制任何温度,它们都是NaN。我还尝试使用不同的选项将数据帧转换为dict(series、split、index、list,但记录会产生错误)。你知道吗

我已经检查了我的日期和温度,数据确实存在,所以它应该找到一些特定日期的地图。你知道吗

我还尝试在映射之前将日期转换为字符串,这也不会导致错误,但它也只为Temperature中的所有内容输出NaN。你知道吗


Tags: andcsvto数据maptransdatadataset
1条回答
网友
1楼 · 发布于 2024-09-27 21:34:52
weather = weather.to_dict('split')

生成具有结构的词典

{'columns': [...],
 'data': [...],
 'index': [...] }

然而,如果你想把map和dictional一起使用,你应该有一个带结构的dictional

{'match_value_1': 2,
 'match_value_2': 3,
  etc. }

假设您不想在开始时更改字典表示的类型,那么您可以稍后转换dict以适应上述方法:

data['Temperature'] = data['trans_date1'].map(dict(weather['data']))

或者从字典重建数据帧并合并它们:

weather = pandas.DataFrame(temps['data'], columns=['Date_Time', 'Mean_Temp_?C'])
df1 = df1.merge(weather, how='inner', left_on='trans_date1', right_on='Date_Time')

这取决于你的逻辑,不管你想执行什么样的合并。如果你需要进一步的帮助,请详细说明。你知道吗

相关问题 更多 >

    热门问题