在python 2.7中使用for循环创建多个数据框 [英] Create multiple dataframe using for loop in python 2.7
本文介绍了在python 2.7中使用for循环创建多个数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个位置列表
["HOME", "Office", "SHOPPING"]
和一个熊猫数据框DF"
and a pandas data frame "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 循环为家庭、办公室、购物创建 3 个不同的数据框,但我无法做到.
I want to create 3 different data frames for HOME, Office, SHOPPING using for loop, but I am not able to do it.
我是 Python 新手
I am new to python
请帮忙.
谢谢露西
推荐答案
使用 groupby()
然后调用它的 get_group()
方法:
Use groupby()
and then call it's get_group()
method:
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:
but I think add global variables in a for loop isn't a good method, you can convert the groupby to a dict by:
d = dict(iter(g))
然后就可以使用d["HOME"]
来获取数据了.
then you can use d["HOME"]
to get the data.
这篇关于在python 2.7中使用for循环创建多个数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文