如何根据其他列的内容选择数据框中的特定数据?

时间:2019-12-02 20:26:32

标签: python pandas qpython

我是熊猫的新手,目前正在尝试使用qPython在平板电脑上的数据集上使用它(临时情况,笔记本电脑已修复)。我有一个csv文件,其中包含按国家,地区,市场和商品标签组织的一组数据,并带有价格,年份和月份的其他列。这些设置如下:

Country | Region |   Market   | Item Label | ... | Price | Year | Month |
Canada  | Quebec | Market No. | Item Name  | ... |  $$$  | 2002 |   1   |
Canada  | Quebec | Market No. | Item Name  | ... |  $$$  | 2002 |   2   |
Canada  | Quebec | Market No. | Item Name  | ... |  $$$  | 2002 |   3   |
Canada  | Quebec | Market No. | Item Name  | ... |  $$$  | 2002 |   4   |

,依此类推。我正在寻找一种按时间绘制这些价格的方法(为了将最后一列有效地合并,我已经在年中增加了month / 12)。

最初,我有一个代码来获取csv数据并将其放入Dictionary中,就像这样:

{Country_Name: {Region_Name: {Market_Name: {Item_Name: {"Price": price_list, "Time": time_list}}}}}

,用于循环访问每个价格和时间清单的键。

但是,使用熊猫很难获得类似的结果:我尝试了几种不同的方法,例如iloc,data [data.Country ==“ Canada”] [data.Region ==“魁北克”] [...等)来过滤每个国家,地区,市场和商品的数据,但是所有这些数据特别慢。数据集相当庞大(大约是12000乘12),所以我不希望立即得到结果,但是我明显缺少什么吗?还是我应该等到拿回笔记本电脑?

编辑:为了尝试提供更多的背景信息,我试图获得多年来和几个月中的价格,以绘制价格的波动情况。我想根据国家,地区,市场和项目分类将它们分开,因此绘制的每条线在一个国家/地区的市场中将是不同的项目。到目前为止,我有以下代码:

def abs_join_paths(*args):
    return os.path.abspath(os.path.join(*args))

def get_csv_data_frame(*path, memory = True):
    return pandas.read_csv(abs_join_paths(*path[:-1], path[-1] + ".csv"), low_memory = memory)

def get_food_data(*path):
    food_price_data = get_csv_data_frame(*path, memory = False)
    return food_price_data[food_price_data.cm_name != "Fuel (diesel) - Retail"]

food_data = get_food_data(data_path, food_price_file_name)

def plot_food_price_time_data(data, title, ylabel, xlabel, plot_style = 'k-'):
    plt.clf()
    plt.hold(True)
    data["mp_year"] += data["mp_month"]/12
    for country in data["adm0_name"].unique():
        for region in data[data.adm0_name == country]["adm1_name"].unique():
            for market in data[data.adm0_name == country][data.adm1_name == region]["mkt_name"]:
                for item_label in data[data.adm0_name == country][data.adm1_name == region][data.mkt_name == market]["cm_name"]:
                    current_data = data[data.adm0_name == country][data.adm1_name == region][data.mkt_name == market][data.cm_name == item_label]
                    #year = list(current_data["mp_year"])
                    #month = list(current_data["mp_month"])
                    #time = [float(y) + float(m)/12 for y, m in zip(year, month)]
                    plt.plot(list(current_data["mp_year"]), list(current_data["mp_price"]), plot_style)
                    print(list(current_data["mp_price"]))
    plt.savefig(abs_join_paths(imagepath, title + ".png"))

Edit2 / tl; dr:我有一堆价格和时间,在一个很长的列表中一个接一个。如何使用熊猫根据其他列的内容将它们拆分?

干杯!

2 个答案:

答案 0 :(得分:0)

我很犹豫,但是似乎您可能正在遍历行(您说您正在使用iloc)。这是大熊猫中最慢的操作。熊猫数据帧已针对系列访问进行了优化。

如果进行绘图,则可以直接将matplotlib与熊猫数据框一起使用,并使用groupby方法来组合数据,而不必遍历数据框的行。

没有更多信息,很难专门回答您的问题。请查看您对问题的评论。

答案 1 :(得分:0)

groupby函数可以达到目的:

def plot_food_price_time_data(data, title, ylabel, xlabel, plot_style = 'k-'):
    plt.clf()
    plt.hold(True)
    group_data = data.groupby(["adm0_name", "adm1_name", "mkt_name", "cm_name"])
    for i in range(len(data)):
        print(data.iloc[i, [1, 3, 5, 7]])
        specific_data = group_data.get_group(tuple(data.iloc[i, [1, 3, 5, 7]]))
        plt.plot(specific_data["mp_price"], specific_data["mp_year"] + specific_data["mp_month"]/12)