gpt4 book ai didi

python - 在 Pandas 中转换列并对其执行函数

转载 作者:行者123 更新时间:2023-12-01 04:46:05 26 4
gpt4 key购买 nike

我正在导入一个文本文件并添加两列,并尝试根据其他两个现有列对两个新创建的列执行一些基本数学运算。我的原始文本文件的数据结构的列长度会定期从 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

最佳答案

您不能在 Series 上使用普通数学函数,因为数组使用 np.sqrt:

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

TypeError 告诉您它需要一个 float 而不是 pandas 系列:

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

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

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

然后为 t 和 r 列生成相同的值,然后串联迭代每个列并选择列:

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

上面显示了如何修改代码以动态方式实现您想要的内容的框架

关于python - 在 Pandas 中转换列并对其执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29378127/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com