首页 > 解决方案 > 'DataFrame' 对象没有属性 'startswith' 错误

问题描述

我正在尝试使用startswith对数据文件的某些部分进行排序,以便可以按名称在 matplotlib 上绘制它们。我用:

mint = open('/Users/brand/Desktop/datafile.txt')
str = ps.DataFrame(mint)
a = str.startswith('MS')
plt.scatter(color[a], light[a], c = 'blue')
b = str.startswith('BH')
plt.scatter(color[b], light[b], c = 'red')
c = str.startswith('RH')
plt.scatter(color[c], light[c], c = 'green')
d = str.startswith('RGB')
plt.scatter(color[d], light[d], c = 'purple')
e = str.startswith('AGB')
plt.scatter(color[e], light[e], c = 'pink')

但是每次我使用不同的模块运行它来打开文件时,它总是有错误:' ' object has no attribute 'startswith'.

那么什么对象有startswith我可以使用的属性呢?

标签: pythondataframe

解决方案


将您的数据框重命名为df_str因为str是python中的关键字。并df_str.str.startswith()应用您的字符串方法

mint = open('/Users/brand/Desktop/datafile.txt')
df_str = ps.DataFrame(mint)[0]
a = df_str.str.startswith('MS')
plt.scatter(color[a], light[a], c = 'blue')
b = df_str.str.startswith('BH')
plt.scatter(color[b], light[b], c = 'red')
c = df_str.str.startswith('RH')
plt.scatter(color[c], light[c], c = 'green')
d = df_str.str.startswith('RGB')
plt.scatter(color[d], light[d], c = 'purple')
e = df_str.str.startswith('AGB')
plt.scatter(color[e], light[e], c = 'pink')

编辑:更改df_str = ps.DataFrame(mint)df_str = ps.DataFrame(mint)[0] 将 Dataframe 转换为 Series


推荐阅读