Home > OS >  Convert Pandas series of multiple object types based on value
Convert Pandas series of multiple object types based on value

Time:03-19

I have the following Pandas series that I want to convert only the values of that aren't -1:

series = pd.Series([-1,
 -1,
 -1,
 -1,
 -1,
 '1:53.461000',
 '1:49.862000',
 '1:48.376000',
 '1:47.814000',
 '1:47.192000'])

I want to convert the non-integer values using the following function:

def get_sec(time_str):
    """Get seconds from time."""
    m, s = str(time_str).split(':')
    return (int(m) * 60)   float(s)

I've tried using np.where(series == -1, -1, series.map(get_sec)) (and other variations of that), but it doesn't work. Often times it returns the ValueError "not enough values to unpack (expected 2, got 1)" - any suggestions on this? Do I need to use some sort of apply function?

CodePudding user response:

Just use a filter:

mask = series != -1
series[mask] = series[mask].apply(get_sec)

Output:

>>> series
0         -1
1         -1
2         -1
3         -1
4         -1
5    113.461
6    109.862
7    108.376
8    107.814
9    107.192
dtype: object
  • Related