我正在尝试在多个列上连接两个数据框。即使所有列都存在于两个数据框中,执行pd.merge时也遇到了关键错误。
当我尝试执行.join时,我得到
"ValueError: len(left_on) must equal the number of levels in the index of "right""
数据框1:
>>data.columns
Index(['weather.description', 'weather.icon', 'weather.id', 'weather.main',
'dt', 'main.pressure', 'main.temp_min', 'main.temp_max', 'main.temp',
'main.humidity', 'main.grnd_level', 'main.sea_level', 'wind.speed',
'wind.deg', 'wind.gust', 'id', 'day', 'month', 'hour', 'dd', 'year'],
dtype='object')
>>data.dtypes
weather.description object
weather.icon object
weather.id int64
weather.main object
dt object
main.pressure float64
main.temp_min float64
main.temp_max float64
main.temp float64
main.humidity int32
main.grnd_level float64
main.sea_level float64
wind.speed float64
wind.deg float64
wind.gust float64
id float64
day object
month object
year object
hour object
dd object
dtype: object
数据框2:
>>df_crime.columns
Index(['beat', 'disposition', 'event_date', 'event_number', 'general_location',
'location_1', 'map_x', 'map_y', 'type', 'type_description', 'ward',
'day', 'year', 'month', 'dd', 'hour'],
dtype='object')
>>df_crime.dtypes
beat object
disposition object
event_date object
event_number object
general_location object
location_1 object
map_x float64
map_y float64
type object
type_description object
ward float64
day object
year object
month object
dd object
hour object
dtype: object
内部联接查询:
result = pd.merge(data,
df_crime[['type_description']],
on=['year','month','dd','hour']
)
错误:
KeyError: 'year'
我在这里想念什么?
答案 0 :(得分:1)
我认为您需要在合并中使用'year','month','dd','hour'
列:
在合并中仅使用df_crime[['type_description']]
时,您会错过其他列。
您的on
有4列,所有列都应出现在您在pd.merge()
内获取的数据帧的切片中
检查docs,您可以在其中使用suffixes=
方法来区分公共列(FYI)