简体   繁体   中英

how to add suffix or prefix to xarray values in python?

I have a set of data in xarray, and I need to add some suffix or prefix to the data/value.

to show what I want to do, I here cite an example that works in pandas: by doing

import pandas as pd
df = pd.DataFrame({'col':['a',0]})
df
df['col'] = 'str' + df['col'].astype(str)

I can change from

>>> df
  col
0   a
1   0

to

>>> df
    col
0  stra
1  str0

but in xarray inintiated as:

import xarray as xr

da = xr.DataArray(['1', '2', '3'], [('x', [0, 1, 2])])

dataset = da.to_dataset(name="foo")

the array would be:

<xarray.Dataset>
Dimensions:  (x: 3)
Coordinates:
  * x        (x) int32 0 1 2
Data variables:
    foo      (x) int32 1 2 3

by using

dataset['foo'].astype(str)

I can change the column to strings:

<xarray.DataArray 'foo' (x: 3)>
array(['1', '2', '3'], dtype='<U11')
Coordinates:
  * x        (x) int32 0 1 2

yet then when I try to add the suffix by adding the suffix string:

dataset['foo'] = dataset['foo'].astype(str) + 'suffix'

I got error:

UFuncTypeError: ufunc 'add' did not contain a loop with signature matching types (dtype('<U11'), dtype('<U11')) -> dtype('<U11')

Traceback (most recent call last):

  File "<ipython-input-9-a74b1524f2e5>", line 1, in <module>
    dataset['foo'] = dataset['foo'].astype(str) + 'suffix'

  File "C:\ProgramData\Anaconda3\lib\site-packages\xarray\core\dataarray.py", line 1972, in func
    if not reflexive

  File "C:\ProgramData\Anaconda3\lib\site-packages\xarray\core\variable.py", line 1674, in func
    if not reflexive

UFuncTypeError: ufunc 'add' did not contain a loop with signature matching types (dtype('<U11'), dtype('<U11')) -> dtype('<U11')

I wonder why this happen and what's the correct way to do it? Thanks

You can use the character module of numpy to add strings.

import xarray as xr
import numpy as np

da = xr.DataArray(['1', '2', '3'], [('x', [0, 1, 2])])
dataset = da.to_dataset(name="foo")

dataset['foo'] = ('x', np.char.add(dataset['foo'].astype(str) ,'suffix') )
dataset

>>>array(['1suffix', '2suffix', '3suffix'], dtype='<U7')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM