2016-02-13 104 views
0

我的位置使用Python中的for循环2.7

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

列表和一个大熊猫数据帧“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 

我想创建一个HOME 3个不同的数据帧中创建多个数据帧,Office,SHOPPING使用for循环,但我无法做到这一点。

我是新来的蟒蛇

请帮助。

感谢 露西

+0

什么是你的问题?你不知道如何编写for循环? – Goyo

+0

我知道如何编写循环。我的问题是如何使用for循环创建3个不同的数据帧,如df1 = DF [DF.Start_Location == locations [0]]。希望这可以帮助 – Lucy

+0

不是。你的代码对我来说很合适。 – Goyo

回答

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转换为字典通过:

d = dict(iter(g)) 

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

+0

的列表中,感谢解决方案,但我想创建这些dfs而不使用read_csv,因为主要的数据帧已经可用,而且如果位置列表更多,可以说20那么在等号的左侧给出名字就会有点整齐。有没有其他方法可以做到这一点? – Lucy

+0

'read_csv()'仅用于演示,不需要调用它。我编辑了使用'globals()'的答案。 – HYRY

+0

谢谢,这个工程 – Lucy

2

我,我一直在寻找

import pandas as pd 
gbl = globals() 
for i in locations: 
gbl['df_'+i] = df[df.Start_Location==i] 

这将创建3个数据帧df_HOME,df_office的答案,df_SHOPPING

感谢,