转换列并在Pandas中对它们执行功能

时间:2015-03-31 20:39:16

标签: python pandas

我正在导入文本文件并添加两列,并尝试基于另外两个现有列对两个新创建的列执行一些基本数学运算。我的原始文本文件的数据结构会定期将列长度从10列更改为7.所以我试图用If else语句来捕获它。但我得到以下错误。我该怎么把它转换成?如何通过列号而不是标题名称来识别列上的功能,而不是mru['t1'] = math.sqrt(mru['r1']**2 + mru['p1']**2)这样的mru['t1'] = math.sqrt(mru[1]**2 + mru[2]**2)

"cannot convert the series to {0}".format(str(converter)))
TypeError: cannot convert the series to <type 'float'>

我的代码是:

mru = pd.read_csv(r"C:\some.txt", skipinitialspace=True, names=['time', 'r1', 'p1', 'h1', 'r2', 'p2', 'h2', 'r3', 'p3', 'h3'])


#Identify colum number
col = len(mru.columns)

#Caluulate Tilt
if col == 10:
    converted = mru[mru.columns[-9:]].convert_objects(convert_numeric=True)
    mru[mru.columns[-9:]] = converted
    mru['t1'] = math.sqrt(mru['r1']**2 + mru['p1']**2)
    mru['t2'] = math.sqrt(mru['r2']**2 + mru['p2']**2)
    mru['t3'] = math.sqrt(mru['r3']**2 + mru['p3']**2)
else:
    converted = mru[mru.columns[-9:]].convert_objects(convert_numeric=True)
    mru[mru.columns[-6:]] = converted
    mru = pd.read_csv(r"C:\Dan\20150330_150831_C.txt", skipinitialspace=True, names=['time', 'r1', 'p1', 'h1', 'r2', 'p2', 'h2'])
    mru['t1']= math.sqrt(mru['r1']**2 + mru['p1']**2)
    mru['t2'] = math.sqrt(mru['r2']**2 + mru['p2']**2)

我的数据片段是:( 10列示例):

15:08:31.898,-0.3000,0.1400,0.0000,-0.3100,0.5300,0.6234,0.3357,-0.1500,0.0000
15:08:32.898,-0.3000,0.1400,0.0000,-0.1500,0.2800,-0.0984,0.0905,0.0100,0.0000

1 个答案:

答案 0 :(得分:2)

您不能在Series上使用普通的数学函数,这些函数是使用np.sqrt:

的数组
import numpy as np
mru['t1'] = np.sqrt(mru['r1']**2 + mru['p1']**2)

TypeError告诉你它正在期待一个浮动而不是一个pandas系列:

TypeError: cannot convert the series to <type 'float'>

至于你的cols命名后的其他问题,你可以使用列表理解来过滤它们:

p_cols = [col for col in df if 'p' in col]

然后只为t和r cols生成相同的内容,然后串联迭代它们并选择cols:

In [76]:

df = pd.DataFrame(columns = ['time', 'r1', 'p1', 'h1', 'r2', 'p2', 'h2', 'r3', 'p3', 'h3'])
df
Out[76]:
Empty DataFrame
Columns: [time, r1, p1, h1, r2, p2, h2, r3, p3, h3]
Index: []
In [83]:

r_cols = [col for col in df if 'h' in col]
p_cols = [col for col in df if 'p' in col]
for i in range(3):
    r = df[r_cols[i]]
    p = df[p_cols[i]]
    t_col = 't'+str(i+1)
    print(r_cols[i], p_cols[i], t_col)
    # do something like thi
    #df[t_col] = np.sqrt(r**2 + p**2)

h1 p1 t1
h2 p2 t2
h3 p3 t3

因此,上面显示了如何修改代码以动态方式实现所需的框架