在python 2.7中使用for循环创建多个数据帧

时间:2016-02-13 01:28:25

标签: python pandas

我有一个地点列表

["HOME", "Office", "SHOPPING"]

和pandas数据框" DF"

Start_Location  End_Location    Date
OFFICE          HOME            3-Apr-15
OFFICE          HOME            3-Apr-15
HOME            SHOPPING    3-Apr-15
HOME            SHOPPING    4-Apr-15
HOME            SHOPPING    4-Apr-15
SHOPPING    HOME            5-Apr-15
SHOPPING    HOME            5-Apr-15
HOME            SHOPPING    5-Apr-15

我想使用for循环为HOME,Office,SHOPPING创建3个不同的数据框,但我无法做到。

我是python的新手

请帮忙。

由于 露

3 个答案:

答案 0 :(得分:3)

我得到了我正在寻找的答案

var data = [['user3', 12], ['user2', 10], ['user1', 5], ['user5', 5], ['user4', 4]],
    lastBalance,
    filtered = data.filter(function (a, i, aa) {
        if (i + 1 < aa.length && a[1] === aa[i + 1][1]) {
            lastBalance = a[1];
            return false;
        }
        return a[1] !== lastBalance;
    });

document.write('<pre>' + JSON.stringify(filtered, 0, 4) + '</pre>');

这将创建3个数据帧df_HOME,df_office和df_SHOPPING

谢谢,

答案 1 :(得分:1)

使用groupby()然后调用它get_group()方法:

import pandas as pd
import io

text = b"""Start_Location  End_Location    Date
OFFICE          HOME            3-Apr-15
OFFICE          HOME            3-Apr-15
HOME            SHOPPING    3-Apr-15
HOME            SHOPPING    4-Apr-15
HOME            SHOPPING    4-Apr-15
SHOPPING    HOME            5-Apr-15
SHOPPING    HOME            5-Apr-15
HOME            SHOPPING    5-Apr-15"""

locations = ["HOME", "OFFICE", "SHOPPING"]

df = pd.read_csv(io.BytesIO(text), delim_whitespace=True)
g = df.groupby("Start_Location")
for name, df2 in g:
    globals()["df_" + name.lower()] = df2

但我认为在for循环中添加全局变量并不是一个好方法,你可以通过以下方式将groupby转换为dict:

d = dict(iter(g))

然后您可以使用d["HOME"]来获取数据。

答案 2 :(得分:0)

您可能有一个字典,并且想根据字典的键将其转换为某些数据框:

gbl = globals()
for keys, values in dictionary.items():
   gbl['df_min'+ str(keys)] = pd.DataFrame(values)
相关问题