J. Rigby
J. Rigby

Reputation: 119

How to concatenate 2 rows of an Astropy Table?

I have created an Astropy Table 'specs' that has columns 'path' and 'filename'.
Here's the first row:

 path                    filename   
 string192              string256
------------------------ --------------------------------     
 RCS0327/KnotB/        rcs0327-knotB-combwC1.txt 

I would like to concatenate these two columns.

 for ii, dum in enumerate(specs['filename]') :
    specs['filename'][ii] =  str(specs['path'][ii]) + str(specs['filename'][ii])

Which fails spectacularly because it truncates the filename. What am I doing wrong? This seems like such a simple operation for a Table.

Upvotes: 0

Views: 296

Answers (2)

Tom Aldcroft
Tom Aldcroft

Reputation: 2542

As of astropy 1.1 there is a replace_column method on Table. So you can do this in one or two lines of actual code. For example:

In [11]: t
Out[11]: 
<Table length=3>
 a    b  
str1 str1
---- ----
   a    b
   b    c
   c    d

In [12]: temp = [row['a'] + row['b'] for row in t]

In [13]: temp
Out[13]: ['ab', 'bc', 'cd']

In [14]: t.replace_column('a', temp)

In [15]: t
Out[15]: 
<Table length=3>
 a    b  
str2 str1
---- ----
  ab    b
  bc    c
  cd    d

Upvotes: 1

J. Rigby
J. Rigby

Reputation: 119

Verbose, but works. One can't just write to specs['filename'], as it is a set width and will truncate. Instead, make a new column, and swap it in.

temp = []
for ii, dum in enumerate(specs['filename']):
    filename_w_path = str(specs['origdir'][ii]) + str(specs['filename'][ii])
    temp.append(filename_w_path)
temp_col = Column(temp, name='fullname')
specs.add_column(temp_col)   # Make a column of the fullname, with path
specs.rename_column('filename', 'old_filename')
specs.rename_column('fullname', 'filename')

Upvotes: 1

Related Questions