【问题标题】:Operations on Columns multiple files Pandas对 Columns 多个文件 Pandas 的操作
【发布时间】:2015-09-13 10:47:22
【问题描述】:

我正在尝试在 Python Pandas 中执行一些算术运算并将结果合并到一个文件中。

Path_1: File_1.csv, File_2.csv, ....

这个路径有几个文件,这些文件应该在时间间隔内增加。以下列

    File_1.csv    |  File_2.csv
    Nos,12:00:00  |  Nos,12:30:00

    123,1451         485,5464
    656,4544         456,4865
    853,5484         658,4584

Path_2: Master_1.csv

Nos,00:00:00
123,2000
485,1500
656,1000
853,2500
456,4500
658,5000

我正在尝试从Path_1 读取.csv 文件的n 数量,并将col[1] 标头时间序列与col[last] 时间序列Master_1.csv 进行比较。

如果Master_1.csv 没有那个时间,它应该从path_1 .csv 文件中创建一个包含时间序列的新列,并更新与col['Nos'] 相关的值,同时从Master_1.csvcol[1] 中减去它们。

如果colpath_1 file 之间的时间存在,则查找col['Nos'],然后将NAN 替换为与col['Nos'] 相关的减去值。

Master_1.csv 中的预期输出

Nos,00:00:00,12:00:00,12:30:00,
    123,2000,549,NAN,
    485,1500,NAN,3964,
    656,1000,3544,NAN
    853,2500,2984,NAN
    456,4500,NAN,365
    658,5000,NAN,-416

我可以理解算术计算,但我无法循环输入 Nostimeseries 我已尝试将一些代码放在一起并尝试解决循环问题。在这种情况下需要帮助。谢谢

import pandas as pd 
import numpy as np

path_1 = '/'
path_2 = '/'

df_1 = pd.read_csv(os.path_1('/.*csv'), Index=None, columns=['Nos', 'timeseries'] #times series is different in every file eg: 12:00, 12:30, 17:30 etc
df_2 = pd.read_csv('master_1.csv', Index=None, columns=['Nos', '00:00:00']) #00:00:00 time series

for Nos in df_1 and df_2:
    df_1['Nos'] = df_2['Nos']
    new_tseries = df_2['00:00:00'] - df_1['timeseries']

merged.concat('master_1.csv', Index=None, columns=['Nos', '00:00:00', 'new_tseries'], axis=0) # new_timeseries is the dynamic time series that every .csv file will have from path_1

【问题讨论】:

    标签: python file csv pandas time-series


    【解决方案1】:

    你可以分三步完成

    1. 将 csv 读入数据框列表
    2. 将数据框合并在一起(相当于 SQL 左连接或 Excel VLOOKUP
    3. 使用矢量减法计算派生列。

    您可以尝试以下代码:

    #read dataframes into a list
    import glob
    L = []
    for fname in glob.glob(path_1+'*.csv'):
       L.append(df.read_csv(fname))
    
    #read master dataframe, and merge in other dataframes
    df_2 = pd.read_csv('master_1.csv')
    for df in L:
       df_2 = pd.merge(df_2,df, on = 'Nos', how = 'left')
    
    #for each column, caluculate the difference with the master column
    df_2.apply(lambda x: x - df_2['00:00:00'])
    

    【讨论】:

    • 这给出了一个错误Traceback (most recent call last): File "main_1.py", line 12, in <module> data_frame.append(df.read_csv(fname)) NameError: name 'df' is not defined
    猜你喜欢
    • 2020-01-17
    • 2019-04-05
    • 2021-07-25
    • 2019-10-18
    • 1970-01-01
    • 1970-01-01
    • 2012-03-05
    • 2022-08-17
    • 2015-04-27
    相关资源
    最近更新 更多