2016-09-15 95 views
0

我有一个熊猫数据框。我有一列可能有空值或字符串值的数组。但是,我在处理如何在此列中存储值时遇到问题。在pandas的列中存储字符串值数组?

这是现在我的代码:

df_completed = df[df.completed] 
df['links'] = None 
for i, row in df_completed.iterrows(): 
    results = get_links(row['nct_id']) 
    if results: 
     df[df.nct_id == row['nct_id']].links = results 
     print df[df.nct_id == row['nct_id']].links 

但是,这两个问题:

  • results是长度为1的阵列,打印输出是无,而不是阵列中,所以我想我必须保存错误的值
  • results是一个较长的数组时,我保存该值的行会产生一个错误:ValueError: Length of values does not match length of index

我在做什么错?

回答

0

我不确定尝试在这样的熊猫中存储数组是否可取,是否考虑尝试序列化数组内容然后存储?

如果存储阵列是你反正以后是什么,那么你就可以用set_value()方法试试,像这样(请确保您nct_id列的D型的护理):

In [35]: df = pd.DataFrame(data=np.random.rand(5,5), columns=list('ABCDE')) 

In [36]: df 
Out[36]: 
      A   B   C   D   E 
0 0.741268 0.482689 0.742200 0.210650 0.351758 
1 0.798070 0.929576 0.522227 0.280713 0.168999 
2 0.413417 0.481230 0.304180 0.894934 0.327243 
3 0.797061 0.561387 0.247033 0.330608 0.294618 
4 0.494038 0.065731 0.538588 0.095435 0.397751 

In [38]: df.dtypes 
Out[38]: 
A float64 
B float64 
C float64 
D float64 
E float64 
dtype: object 

In [39]: df.A = df.A.astype(object) 

In [40]: df.dtypes 
Out[40]: 
A  object 
B float64 
C float64 
D float64 
E float64 
dtype: object 

In [41]: df.set_value(0, 'A', ['some','values','here']) 
Out[41]: 
         A   B   C   D   E 
0 [some, values, here] 0.482689 0.742200 0.210650 0.351758 
1    0.79807 0.929576 0.522227 0.280713 0.168999 
2    0.413417 0.481230 0.304180 0.894934 0.327243 
3    0.797061 0.561387 0.247033 0.330608 0.294618 
4    0.494038 0.065731 0.538588 0.095435 0.397751 

希望这有助于!