Skip to main content
 首页 » 编程设计

python之切片我的数据框返回意外结果

2024年12月31日8kenshinobiy

我有 13 个 CSV 文件,其中包含格式不寻常的账单信息。一天中每 30 分钟记录一次多个读数。五天记录在彼此旁边(列)。然后接下来的五天记录在它下面。使事情变得更复杂的是,每天的第一个 KVAR 记录显示星期几、日期和计费日。

下图是一个小例子。但是,假设 KW、KVAR 和 KVA 在继续大约 50 行之后再重复 3 次。

我的目标是创建一个简单的 python 脚本,将数据放入包含以下列的数据框中:DATE、TIME、KW、KVAR、KVA 和 DAY。

问题是我的脚本在前五天后返回 KW、KVAR 和 KVA 数据的 NaN 数据(这与 for 循环的新实例相关)。令我感到奇怪的是,当我尝试打印出相同的范围时,我得到了我期望的数据。

我的代码如下。我已经包含了评论以帮助进一步解释事情。我还有一个函数示例输出示例。

def make_df(df): 
 
    #starting values 
    output = pd.DataFrame(columns=["DATE", "TIME", "KW", "KVAR", "KVA", "DAY"]) 
    time = df1.loc[3:50,0] 
    val_start = 3 
    val_end = 51 
    date_val = [0,2] 
    day_type = [1,2] 
 
    # There are 7 row movements that need to take place.  
    for row_move in range(1,8): 
        day = [1,2,3] 
        date_val[1] = 2 
        day_type[1] = 2 
 
        # There are 5 column movements that take place. 
 
        # The basic idea is that I would cycle through the five days, grab their data in a temporary dataframe, 
        # and then append that dataframe onto the output dataframe 
        for col_move in range(1,6): 
            temp_df = pd.DataFrame(columns=["DATE", "TIME", "KW", "KVAR", "KVA", "DAY"]) 
            temp_df['TIME'] = time 
 
            #These are the 3 values that stop working after the first column change 
            # I get the values that I expect for the first 5 days 
            temp_df['KW'] = df.iloc[val_start:val_end, day[0]] 
            temp_df['KVAR'] = df.iloc[val_start:val_end, day[1]] 
            temp_df['KVA'] = df.iloc[val_start:val_end, day[2]] 
 
            # These 2 values work perfectly for the entire data set 
            temp_df['DAY'] = df.iloc[day_type[0], day_type[1]] 
            temp_df["DATE"] = df.iloc[date_val[0], date_val[1]] 
 
            # trouble shooting 
            print(df.iloc[val_start:val_end, day[0]]) 
            print(temp_df) 
 
            output = output.append(temp_df) 
 
            # increase values for each iteration of row loop. 
            # seems to work perfectly when I print the data 
            day = [x + 3 for x in day] 
            date_val[1] = date_val[1] + 3 
            day_type[1] = day_type[1] + 3 
 
        # increase values for each iteration of column loop 
        # seems to work perfectly when I print the data 
        date_val[0] = date_val[0] + 55 
        day_type [0]= day_type[0] + 55 
 
        val_start = val_start + 55 
        val_end = val_end + 55 
 
    return output 
 
test = make_df(df1) 

下面是一些示例输出。它显示了第五天(或 for 循环中第一个列移位实例)后数据开始分解的位置。我做错了什么?

请您参考如下方法:

可能是 pd.append 需要为数值匹配行索引。

import pandas as pd 
import numpy as np 
output = pd.DataFrame(np.random.rand(5,2), columns=['a','b'])  # fake data  
output['c'] = list('abcdefghij')  # add a column of non-numerical entries 
 
tmp = pd.DataFrame(columns=['a','b','c']) 
tmp['a'] = output.iloc[0:2, 2]  
tmp['b'] = output.iloc[3:5, 2]  # generates NaN 
tmp['c'] = output.iloc[0:2, 2]  
data.append(tmp) 

(初始响应)

df1 是什么样子的? df.iloc[val_start:val_end, day[0]] 在第五天之后是否有任何问题?这些代码没有显示您如何从 csv 文件或 df1 本身读取数据。

我的猜测:如果 val_start:val_end 在第六天给出无效索引,或者 df1 在第五天之后恰好格式错误,df.iloc[ val_start:val_end, day[0]] 将返回一个空的 Series 对象,并可能进入 temp_df。 iloc 不报告无效的行索引,但类似的列索引会触发 IndexError。

import numpy as np 
import pandas as pd 
df = pd.DataFrame(np.random.rand(5,3), columns=['a','b','c'], index=np.arange(5))  # fake data 
df.iloc[0:2, 1]  # returns the subset 
df.iloc[100:102, 1]  # returns: Series([], Name: b, dtype: float64) 

有点偏离主题,但我建议预处理 csv 文件而不是处理 Pandas DataFrame 中的索引,因为原始格式有点复杂。按日期对数据进行切片,然后使用 pd.melt 或 pd.groupby 将它们整形为您喜欢的格式。或者,如果坚持使用 Pandas I/O,也可以尝试多索引。