首页 文章

基于标签的索引Pandas(.loc)

提问于
浏览
2

我最近已经意识到链式赋值的危险,我正在尝试使用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 回答

  • 0

    您可能遇到了dtype问题 . 以下代码适用于我:

    import pandas as pd
    data = {'working_hr': {3: 9.0}, 'order_no': {3: 731231}}
    df = pd.DataFrame.from_dict(data, dtype=object)
    

    然后:

    >>> df.loc[3, 'order_no'] = [1, 2]
    >>> df
      order_no working_hr
    3   [1, 2]          9
    

    注意 dtype=object . 这可能是您缩短DataFrame时错误消失的原因,特别是如果您(例如)浮点数为_64577 . 因此,请检查您的混合类型列是否确实设置为dtype object .

    同样适用于您提供的CSV:

    >>> df = pandas.read_clipboard(sep='\t', index_col=0)
    >>> df
            buyer          order_no                                 item         smv
    0         H&M            992754                        Cole tank top        6.17
    1         H&M            859901                         Thilo Bottom        8.55
    2         H&M            731231               Palma Short Sleeve Tee        5.65
    3         H&M     731231/339260                      Palma Price Tee        5.65
    4         H&M     859901/304141  Thilo Paijama Set top/Elva Tank Top   5.80/5.58
    5         H&M            768380                       Folke Tank Top           6
    6         H&M     596701/590691                        Paul Rock Tee        7.65
    7    H&M/Mexx  731231/KIEZ-P002        Palma Short Sleeve Tee/Shorts  5.65/12.85
    8         NaN               NaN                                  NaN         NaN
    9  Ginatricot     512008/512009                           J.Tank top         4.6
    >>> df.loc[3, 'order_no'] = str(df.loc[3, 'order_no']).split('/')
    >>> df
            buyer          order_no                                 item         smv
    0         H&M            992754                        Cole tank top        6.17
    1         H&M            859901                         Thilo Bottom        8.55
    2         H&M            731231               Palma Short Sleeve Tee        5.65
    3         H&M  [731231, 339260]                      Palma Price Tee        5.65
    4         H&M     859901/304141  Thilo Paijama Set top/Elva Tank Top   5.80/5.58
    5         H&M            768380                       Folke Tank Top           6
    6         H&M     596701/590691                        Paul Rock Tee        7.65
    7    H&M/Mexx  731231/KIEZ-P002        Palma Short Sleeve Tee/Shorts  5.65/12.85
    8         NaN               NaN                                  NaN         NaN
    9  Ginatricot     512008/512009                           J.Tank top         4.6
    
  • 5

    更短的错误提升代码供参考(直到OP在他的问题中包括它):

    import pandas as pd
    data = {'working_hr': {3: 9.0}, 'order_no': {3: 731231}}
    df = pd.DataFrame.from_dict(data)
    df.loc[3, 'order_no'] = [1,2] # raises error
    

    检查代码,列表值 [1,2] 被_setitem_with_indexer视为列表,我无法看到如何将这个问题作为标量处理来避免 .

相关问题