【问题标题】:'function' object has no attribute 'str' in pandas'function'对象在熊猫中没有属性'str'
【发布时间】:2020-06-23 21:57:41
【问题描述】:

我正在使用下面的代码来读取和拆分由 / 分隔的 csv 文件字符串

DATA IS 
SRC_PATH                        TGT_PATH
/users/sn/Retail                /users/am/am
/users/sn/Retail Reports/abc    /users/am/am
/users/sn/Automation            /users/am/am
/users/sn/Nidh                  /users/am/xzy

将熊猫导入为 pd

df = pd.read_csv('E:\RCTemplate.csv',index_col=None, header=0)
s1 = df.SRC_PATH.str.split('/', expand=True)

我在 s1 中获得了正确的拆分数据,但是当我要对单行执行类似操作时,它会抛出错误“'function' object has no attribute 'str'”

下面的代码出错了

df2= [(df.SRC_PATH.iloc[0])]
df4=pd.DataFrame([(df.SRC_PATH.iloc[0])],columns = ['first'])
newvar = df4.first.str.split('/', expand=True)

【问题讨论】:

标签: python pandas dataframe


【解决方案1】:

Pandas 认为您正在尝试访问方法 dataframe.first()

这就是为什么最好使用硬括号来访问数据框列而不是 .column 访问

df4['first'].str.split() 而不是df4.first.str.split()

并不是说这会导致常见问题,例如名为 'name' 的列最终成为数据框的 name 属性以及许多其他问题

【讨论】:

  • 谢谢@G.Anderson,它成功了。我一定会记住的。我想知道为什么它没有在 s1 抛出错误??
  • 因为. 列访问有效的python,并且数据框没有方法或属性.SRC_PATH()。问题是你的列名'first',隐藏了内置的.first 方法
  • 谢谢你。我会潜水以避免这些。
猜你喜欢
  • 2016-08-19
  • 2018-07-11
  • 2019-10-02
  • 1970-01-01
  • 2019-02-28
  • 1970-01-01
  • 2021-09-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多