首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Pandas KeyError on pd.merge,即使在数据仓库中存在相同的列时

Pandas KeyError on pd.merge,即使在数据仓库中存在相同的列时
EN

Stack Overflow用户
提问于 2019-01-04 15:50:34
回答 1查看 887关注 0票数 1

我试图在多个列上加入两个数据格式。即使所有列都存在于两个数据格式中,我在执行pd.merge时也会得到一个关键错误。

当我尝试做一个"ValueError: len(left_on) must equal the number of levels in the index of "right""时,我就得到了.join

Dataframe 1:

代码语言:javascript
复制
>>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

Dataframe 2:

代码语言:javascript
复制
>>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

内部连接查询:

代码语言:javascript
复制
result = pd.merge(data,
                  df_crime[['type_description']],
                  on=['year','month','dd','hour']
                  )

错误:

代码语言:javascript
复制
KeyError: 'year'

我在这里错过了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-04 15:57:11

我认为您需要合并中的'year','month','dd','hour'列:

当您在合并中只获取df_crime[['type_description']]时,您将忽略其他列。

您的on有4列,所有列都应该在pd.merge()中的数据帧中显示。

检查文档,在这里您可以使用suffixes=方法来区分公共列(FYI)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54042178

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档