我最近已经意识到链式赋值的危险,我正在尝试使用loc [rowindex,colindex]在pandas中使用正确的索引方法 . 我正在使用混合数据类型(混合在同一系列的np.float64和列表和字符串中) - 这是不可避免的 . 我有一个整数索引
我正在通过数据框运行以下循环
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('/')
工作正常,但这是我试图避免的链式分配类型,因为它给了我其他地方的问题 .
这就是为什么我认为这只是一个语法错误 .
对不起,现在这个非常好的问题
2 回答
您可能遇到了dtype问题 . 以下代码适用于我:
然后:
注意
dtype=object
. 这可能是您缩短DataFrame时错误消失的原因,特别是如果您(例如)浮点数为_64577 . 因此,请检查您的混合类型列是否确实设置为dtypeobject
.同样适用于您提供的CSV:
更短的错误提升代码供参考(直到OP在他的问题中包括它):
检查代码,列表值
[1,2]
被_setitem_with_indexer视为列表,我无法看到如何将这个问题作为标量处理来避免 .