【问题标题】:Python Pandas: AttributeError: 'str' object has no attribute 'loc'Python Pandas:AttributeError:'str'对象没有属性'loc'
【发布时间】:2017-09-20 17:29:36
【问题描述】:

使用数据框 df:

Count
1
2
3
4
5

想要添加第二列,将 3 以上的所有内容归类为“4+” - 需要输出:

Count | Category
1        1
2        2
3        3
4        4+
5        4+

这是我的代码:

df['Category'] = df['Count']
df = df.loc[df['Count'] > 3, 'Category'] = '4+'

我得到这个错误:

AttributeError: 'str' object has no attribute 'loc'

【问题讨论】:

  • 仅供参考 - 您也可以使用 df['Category'] = np.where(df['Count'] < 4, df['Count'], '4+')

标签: python string pandas error-handling


【解决方案1】:

随你去

df['Category'] = df['Count']
df.loc[df['Count'] > 3, 'Category'] = '4+'

【讨论】:

  • 谢谢 - 你介意解释一下,我做错了什么吗?
  • 我刚刚尝试不使用“df=”,但我得到了同样的错误
  • 我为什么不使用 df=?
  • 您在执行 df.loc[df['Count'] > 3, 'Category'] = '4+' 时已经使用 loc 进行分配。当你添加 df = .... 时,你试图在同一个语句中分配两次,这显然是行不通的
  • 这个答案真的对你有用吗@jeangelj?我试了一下,得到了错误ValueError: invalid literal for int() with base 10: '4+'
【解决方案2】:

你可以试试:

import pandas as pd
df = pd.DataFrame({"Count": [1,2,3,4,5]})
df["Category"] = df["Count"].apply(str)
df["Category"][df['Count'] > 3] = "4+"

输出将是:

>>> df
   Count Category
0      1        1
1      2        2
2      3        3
3      4       4+
4      5       4+

【讨论】:

  • 它抛出 SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
  • 您是尝试了我所说的唯一示例还是使用了自己的数据框?如果您的数据框有数字,这应该可以工作。
  • 请通过此链接了解settingwithcopy warning 以及为什么要使用loc。 stackoverflow.com/questions/20625582/…
  • 嗯,这很奇怪。我在pythonanywhere.com 上尝试了 Python 2.7 和 3.3,但我的选项没有收到任何警告。
猜你喜欢
  • 1970-01-01
  • 2020-12-18
  • 2017-06-08
  • 2016-09-14
  • 2017-06-04
  • 2013-10-28
  • 2022-01-21
  • 2018-12-01
  • 2015-09-30
相关资源
最近更新 更多