首页 > 解决方案 > 在新版 pandas 中改造 pandas.Dataframe.ix

问题描述

您好,我进入更新使用 pandas 0.23.4 的代码行 data ['dt'] = pd.DatetimeIndex (data.ix [:, 0]) 在升级 pandas 和 python 后给我带来错误。据研究,这个函数(pandas.dataframe.ix)已被移除。可以用什么方法来代替它?基本上代码的作用,它确实意味着每小时的值,它写入一个新文件夹

import pandas as pd
from msvcrt import getch
from os import listdir

#reading file and user input
file_name = [filename for filename in listdir() if (".csv" or ".txt") in filename]

if not file_name:
    print("\nThere are no .csv files in folder")
    print(listdir())
else:
    for file in file_name:

        print("\nParsing {}".format(file))

        typ = file[-4:] #get extension of file

        if (typ == ".csv"):
            data = pd.read_csv(file, sep=';', encoding='utf-8', skiprows = 2)
            #subcase for different type of separators
            if len(data.columns) == 1:
                data = pd.read_csv(file, sep=',', encoding='utf-8', skiprows = 2)

        else:
            data = pd.read_csv(file, sep=';', encoding='utf-16', skiprows = 2)
            if len(data.columns) == 1:
                data = pd.read_csv(file, sep=',', encoding='utf-16', skiprows = 2)


        data['Valeur'] = data['Valeur'] / 1000
        data['dt'] = pd.DatetimeIndex(data.ix[:, 0])
        data = data.set_index(data['dt']).tz_localize("UTC").tz_convert("Europe/Paris")
        data['Valeur'].resample('1h').mean().to_csv("output//{}_0.csv".format(file[:-4].split(".")[0]))

print("\nPress any key (other than ALT) to exit")
getch()

初始文件中的数据: 初始文件中的数据

最后结果: 最后结果

标签: pythonpython-3.xpandasdataframe

解决方案


我找到了解决方案

import pandas as pd
from msvcrt import getch
from os import listdir

#reading file and user input
file_name = [filename for filename in listdir() if (".csv" or ".txt") in filename]

if not file_name:
    print("\nThere are no .csv files in folder")
    print(listdir())
else:
    for file in file_name:

        print("\nParsing {}".format(file))

        typ = file[-4:] #get extension of file

        if (typ == ".csv"):
            data = pd.read_csv(file, sep=';', encoding='utf-8', skiprows = 2)
            #subcase for different type of separators
            if len(data.columns) == 1:
                data = pd.read_csv(file, sep=',', encoding='utf-8', skiprows = 2)

        else:
            data = pd.read_csv(file, sep=';', encoding='utf-16', skiprows = 2)
            if len(data.columns) == 1:
                data = pd.read_csv(file, sep=',', encoding='utf-16', skiprows = 2)


        data['Valeur'] = data['Valeur'] / 1000

        data['dt'] = pd.to_datetime(data.iloc[:, 0],utc=True)

        data = data.set_index(pd.DatetimeIndex(data['dt'])).tz_convert("Europe/Paris")



        data['Valeur'].resample('1h').mean().to_csv("output//{}_0.csv".format(file[:-4].split(".")[0]),header=False)
        print("fin de Reshaper, ciao!")

print("\nPress any key (other than ALT) to exit")
getch()

推荐阅读