我最近意识到了链式赋值的危险性,我正在尝试使用loc[rowindex,colindex]在熊猫中使用正确的索引方法。我正在处理混合数据类型(在np.float64和list和string的同一系列中混合)-这是不可避免的。我有一个整数索引
我正在通过一个数据帧运行以下循环
Count = 0
for row in DF.index:
print row
if '/' in str(DF.order_no[row]) and '/' not in str(DF.buyer[row]) and '/' not in str(DF.buyer[row])\
and '/' not in str(DF.smv[row]) and '/' not in str(DF.item[row]):
DF.loc[row, 'order_no'] = str(DF.loc[row, 'order_no']).split('/')
Count +=1
计数
返回错误:
TypeError: object of type 'int' has no len()
我做错什么了?
在这个循环中,我可以做到:
print DF.loc[row, 'order_no']
以及
print DF.loc[row, 'order_no'] == str(DF.loc[row, order_no]).split('/')
但不是
DF.loc[row, 'order_no'] = str(DF.loc[row, order_no]).split('/')
使用print语句,我看到它卡在第3行,但是:
DF.loc[3, 'order_no']
工作得很好。
帮助通知。
编辑
解决方法如下:
Count = 0
Vals = []
Ind = []
for row in DF.index:
if '/' in str(DF.order_no[row]) and '/' not in str(DF.buyer[row]) and '/' not in str(DF.buyer[row])\
and '/' not in str(DF.smv[row]) and '/' not in str(DF.item[row]):
Vals.append(DF.order_no[row].split('/'))
Ind.append(row)
Count +=1
DF.loc[Ind, 'order_no'] = Vals
换句话说,我可以创建一个要修改的值的列表,然后使用.loc更改它们。这很好,这让我相信问题不在于我要分配的值,也不在于分配过程本身。
下面是我正在处理的数据类型的一个示例:据我所知,代码在第3行和第9行失败。抱歉,它的csv格式,但这是我如何阅读成熊猫。
https://www.dropbox.com/s/zuy8pj15nlhmcfb/EG2.csv
如果完成以下操作,则使用该数据:
EG = pd.reas_csv('EG.csv')
EG.loc[3, 'order_no'] = str(EG.loc[3, 'order_no']).split('/')
因错误而失败
object of type 'int' has no len()
但是
EG['order_no'][3] = str(EG.loc[3, 'order_no']).split('/')
工作很好,但这是我试图避免的链分配类型,因为它给了我其他地方的问题。
这就是为什么我认为这只是一个语法错误。
很抱歉现在有个不舒服的问题
您可能遇到了数据类型问题。以下代码对我有效:
然后:
注意
dtype=object
。这可能是缩短数据帧时错误消失的原因,特别是在从csv读取数据时。在许多情况下(例如从CSV读取),pandas尝试推断数据类型并选择最具体的类型。如果dtype是object,则可以将列表指定为值,但如果它是float64(例如)。因此,请检查您的混合类型列是否真的设置为dtypeobject
。同样适用于您提供的CSV:
较短的错误提示代码供参考(直到OP将其包含在问题中):
在检查代码时,列表值
[1,2]
由带有列表索引器的setitem处理,对于作为标量处理的值,我看不出如何避免这个问题。相关问题 更多 >
编程相关推荐