Pandas .loc return 一些空数组所以我无法获取它们的值

Pandas .loc return some empty arrays so I can't get their values

我将信息分成两个 table。我想从 table profile 中的 Register Number 列中获取信息,并将其放入我刚刚创建的 Delivers 列中,放入 table consumption,通过在 Cod. Deliver profileCod. agent profile 列中使用信息 - 对于相同的交付是相同的。我使用以下代码来完成:

consumption['Delivers'] = ''
for idx, x in consumption['Cod. Deliver profile'].iteritems():
    consumption['Delivers'].iloc[idx] = profile.loc[profile['Cod. agent profile'] == x, 'Register Number'].values

问题是方法 .values returns a Numpy array,这不是我想要的 - 如下所示。每个单元格应该只有一个字符串类型的值,当没有要设置的值时,为空或其他 - 但没有括号!

29                  []  
30                  []  
31   [6981180000116.0]   
42    [357038000116.0]  
43                  []  
44  [28152650000171.0]  

如果我使用 .item() 我会收到以下错误: ValueError: can only convert an array of size 1 to a Python scalar

如果我使用 .iloc[0],我会得到以下信息: IndexError: single positional indexer is out-of-bounds

如何解决这个问题?

正如 Rutger 在评论中指出的那样,在创建包含数组作为值的 consumption['Delivers'] 列之后,您只需要使用 apply 方法提取值并将它们转换为字符串类型,并且 '0' 如果是空数组:

consumption['Delivers'] = ''
for idx, x in consumption['Cod. Deliver profile'].iteritems():
    consumption['Delivers'].iloc[idx] = profile.loc[profile['Cod. agent profile'] == x, 'Register Number'].values

consumption['Delivers'] = consumption['Delivers'].apply(lambda x: str(x[0]) if len(x) > 0 else '0')

做同样事情的另一种方法是:

consumption['Delivers'] = ''
for idx, x in consumption['Cod. Deliver profile'].iteritems():
     if len(profile.loc[profile['Cod. agent profile'] == x, 'Register Number'])>0:    
         consumption['Delivers'].iloc[idx] = profile.loc[profile['Cod. agent profile'] == x, 'Register Number'].values[0]
     else:
         0