通过重新索引将行插入数据帧

2024-10-01 02:18:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个dataset 以温度为一列。由于加热器的工作方式,数据中存在许多空白。为了使不同的数据集直接具有可比性,我想填写这些缺失的温度,并在另一列中添加相应的nan。你知道吗

我试着使用这里给出的答案,这似乎正是我想要的:link。 但这不起作用-我得到了一个数据框,里面有我想要的新温度值,但相应的数据已经消失了:

import pandas as pd 
import numpy as np           
A1 = pd.read_table('Test data.tsv', encoding='ISO-8859-1', header = 2) 
A1.columns = ['time',2,3,4,5,6,7,'freq',9,10,11,12,13,'temp',15,16,17,18,19] 
A1truncated = A1[A1.temp >= 25]; A1truncated=A1truncated[A1truncated.temp <= 350.1]
A1averaged = A1truncated.groupby(['temp'], as_index=False)['freq'].mean() 
A1averaged = np.around(A1averaged, decimals=1)

A1averaged.set_index('temp') 
new_index = pd.Index(np.arange(25, 350, 0.1), name='temp')
A1indexed = A1averaged.set_index('temp').reindex(new_index).reset_index() 

将我的19列转换为1列,其中温度作为索引(a1平均),然后转换为2列,其中包含新的温度列表和一列空数据(a1索引)。 你知道为什么这样不行吗?或者另一种方法来做同样的事情?你知道吗


Tags: 数据importnewindexa1asnp温度
1条回答
网友
1楼 · 发布于 2024-10-01 02:18:19

带浮点的索引可能有问题,不一致可能是因为浮点精度。所以我用littlehack-Int64Index代替了Float64Index。你知道吗

我试着用更简单的方法设置子集:

A1truncated = A1[(A1.temp >= 25) & ( A1.temp <= 350.1)]

然后省略第一组索引,因为它设置了两次:

A1averaged.set_index('temp')

new_index设置为Int64Index

new_index = pd.Index(np.arange(250, 3500), name='temp')

使用Int64Index乘列temp10,最后一列除以10。你知道吗

A1averaged['temp'] = A1averaged['temp'] * 10
A1indexed['temp'] = A1indexed['temp'] / 10

总之:

import pandas as pd 
import numpy as np           
A1 = pd.read_table('Test data.tsv', encoding='ISO-8859-1', header = 2) 

A1.columns = ['time',2,3,4,5,6,7,'freq',9,10,11,12,13,'temp',15,16,17,18,19] 

A1truncated = A1[(A1.temp >= 25) & ( A1.temp <= 350.1)]

A1averaged = A1truncated.groupby(['temp'], as_index=False)['freq'].mean() 
A1averaged = np.around(A1averaged, decimals=1)
new_index = pd.Index(np.arange(250, 3500), name='temp')

A1averaged['temp'] = A1averaged['temp'] * 10
A1indexed = A1averaged.set_index('temp').reindex(new_index).reset_index()
A1indexed['temp'] = A1indexed['temp'] / 10
print A1indexed.tail()
#       temp       freq
#3245  349.5  5830065.6
#3246  349.6  5830043.5
#3247  349.7  5830046.3
#3248  349.8  5830025.3
#3249  349.9  5830015.6

相关问题 更多 >