【问题标题】:TypeError when concatenating two pandas DataFrames连接两个熊猫数据帧时出现类型错误
【发布时间】:2020-07-05 18:59:54
【问题描述】:

背景 -
我有两个 pandas DataFrame,如下 -

restaurant_df

还有 zipcodes_df:

问题 -
两个 DataFrame 的行数相同,均为 130,但是我在尝试将它们合并在一起时遇到了问题。

我的代码 -
我使用此代码来尝试将数据帧连接在一起。
pd.concat([restaurant_df, zipcodes_df['zipcode']])
由于我的数据帧没有相同的列,我认为这是会工作的。

我遇到了错误 -

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-141-c7df07518b82> in <module>
----> 1 pd.concat([restaurant_df, zipcodes_df['zipcode']])

~/anaconda3/envs/DataScience/lib/python3.7/site-packages/pandas/core/reshape/concat.py in concat(objs, axis, join, ignore_index, keys, levels, names, verify_integrity, sort, copy)
    279         verify_integrity=verify_integrity,
    280         copy=copy,
--> 281         sort=sort,
    282     )
    283 

~/anaconda3/envs/DataScience/lib/python3.7/site-packages/pandas/core/reshape/concat.py in __init__(self, objs, axis, join, keys, levels, names, ignore_index, verify_integrity, copy, sort)
    355                     "only Series and DataFrame objs are valid".format(typ=type(obj))
    356                 )
--> 357                 raise TypeError(msg)
    358 
    359             # consolidate

TypeError: cannot concatenate object of type '<class 'method'>'; only Series and DataFrame objs are valid

帮助:
预期结果应该是 zipcodes_df 中添加到 restaurants_df 末尾(或理想情况下,在“longitude”之后)的一列。
提前感谢所有花时间提供帮助的人!

【问题讨论】:

  • type(restaurant_df) 和 type(zipcodes_df['zipcode']) 在 pd.concat 之前打印出什么?
  • 根据下面的 cmets 和上面的错误。我怀疑resturants_df 设置不正确。 resturants_df 不是数据框。

标签: python pandas jupyter-lab


【解决方案1】:

如果你只是想根据索引粘贴列,你可以这样做

restaurant_df['zipcode'] = zipcodes_df.zipcode

要使用不同的连接选项,请查看以下方法的how 参数:

restaurant_df.merge(zipcodes_df.zipcode, left_index=True, right_index=True)

【讨论】:

  • 感谢您的建议。不幸的是,我得到一个 AttributeError: 'function' object has no attribute 'merge'
  • restaurant_dfzipcodes_df有哪些类型?
【解决方案2】:

我学到了两个教训
1。包括您的所有代码,以帮助成员有效地做出贡献(我没有这样做)。
2。 pd.read_csv() 不会将 .csv 读入 DataFrame

解决方案:
restaurant_df 最初是从 .csv 文件中读取的。我从未真正将 .csv 作为 DataFrame 读取。我添加了这行代码,它现在可以工作了:

restaurant_df = pd.read_csv('raw.csv')

和...

restaurant_df = pd.DataFrame(restaurant_df)

【讨论】:

    猜你喜欢
    • 2019-10-19
    • 2020-01-20
    • 2017-03-05
    • 2016-10-18
    • 2021-06-17
    • 2017-02-14
    • 1970-01-01
    • 2017-10-15
    • 1970-01-01
    相关资源
    最近更新 更多