简体   繁体   中英

Converting Pandas Series Strings to Float

I have a dataFrame, df, with one of the columns::

print(df['MJD_DUPLICATE'])

0         (0, 56238, -1, -1, -1, -1, -1, -1, -1, -1, -1,...
1         (-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1...
2         (0, 56269, -1, -1, -1, -1, -1, -1, -1, -1, -1,...

Simply put, how do I convert this to a float in order to plot it up?

b = df.astype(float)

doesn't work neither does:

for i in range(len(mjds)):
    mjds[i] = [float(x) for x in mjds[i]]

Thanks!!

NB::

print(df['MJD_DUPLICATE'][0:][0:0])

(0, 56279, 0, 56539, 0, 56957, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1)
Series([], Name: MJD_DUPLICATE, dtype: object)

您是否尝试在数据框中创建一个新列,该列为浮点数,然后针对该列进行绘制?

df['MJD_DUPLICATE_float'] = df['MJD_DUPLICATE'].astype(float)

Write a function that transforms the individual row values then use .apply()

data = {'a':[(' 1 ',' 2 ',' 3 '), ('2','3','4'), (3,4,5)],
        'b':[('1','2','3'), ('2','3','4'), ('3','4','5')]}

df = pd.DataFrame(data)

def f(thing):
    return tuple(float(n) for n in thing)

converted = df['a'].apply(f)
df['a'] = converted



>>> converted
0    (1.0, 2.0, 3.0)
1    (2.0, 3.0, 4.0)
2    (3.0, 4.0, 5.0)
Name: a, dtype: object
>>> df
                 a          b
0  (1.0, 2.0, 3.0)  (1, 2, 3)
1  (2.0, 3.0, 4.0)  (2, 3, 4)
2  (3.0, 4.0, 5.0)  (3, 4, 5)
>>>

If your data looks like this

data = {'a':['''(1,2,3)''', '''(2,3,4)''', '''(3,4,5)'''],
        'b':['''(1,2,3)''', '''(2,3,4)''', '''(3,4,5)''']}

Change your function to deal with it

def f(thing):
        thing = thing.strip()
        thing = thing.replace('(', '')
        thing = thing.replace(')', '')
        thing = thing.split(',')
        return tuple(float(n) for n in thing)

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