将Pandas系列字符串转换为浮点数

时间:2017-10-13 19:14:01

标签: python pandas series string-conversion

我有一个dataFrame,df,其中一列::

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,...

简单地说,如何将其转换为浮点数以便绘制它?

b = df.astype(float)

既不工作也是:

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

谢谢!

N.B。::

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)

2 个答案:

答案 0 :(得分:0)

您是否尝试在数据框中创建一个新的列,该数据框是一个浮点数然后根据该数据进行绘图?

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

答案 1 :(得分:0)

编写一个转换单个行值的函数,然后使用.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)
>>>

如果您的数据看起来像这样

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

更改您的功能以处理它

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