Python:Pandas - 基于列值分离数据框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27900733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:50:06  来源:igfitidea点击:

Python: Pandas - Separate a Dataframe based on a column value

pythonpandas

提问by user1452759

Suppose I have a dataframe as shown below:

假设我有一个如下所示的数据框:

in:
mydata = [{'subid' : 'B14-111', 'age': 75, 'fdg':1.78},
          {'subid' : 'B14-112', 'age': 22, 'fdg':1.56},]
df = pd.DataFrame(mydata)

out:
       age   fdg    subid
    0   75  1.78  B14-111
    1   22  1.56  B14-112

I want to separe the dataframe to two different dataframes based on the "age" column, as shown below:

我想根据“年龄”列将数据框分成两个不同的数据框,如下所示:

out:
   df1: 
           age   fdg    subid
        0   75  1.78  B14-111

   df2:

           age   fdg    subid
        1   22  1.56  B14-112

How can I achieve this?

我怎样才能做到这一点?

回答by EdChum

We can do this directly using boolean condition as the filter:

我们可以直接使用布尔条件作为过滤器来做到这一点:

In [5]:

df1 = df[df.age == 75]
df2 = df[df.age == 22]
print(df1)
print(df2)
   age   fdg    subid
0   75  1.78  B14-111
   age   fdg    subid
1   22  1.56  B14-112

but if you have more age values perhaps you want to group them:

但是如果你有更多的年龄值,也许你想把它们分组:

In [13]:
# group by the age column
gp = df.groupby('age')
# we can get the unique age values as a dict where the values are the key values
print(gp.groups)
# we can get a specific value passing the key value for the name
gp.get_group(name=75)
{75: [0], 22: [1]}
Out[13]:
   age   fdg    subid
0   75  1.78  B14-111

We can also get the unique values and again use this to filter the df:

我们还可以获取唯一值并再次使用它来过滤 df:

In [15]:

ages = df.age.unique()
for age in ages:
    print(df[df.age == age])
   age   fdg    subid
0   75  1.78  B14-111
   age   fdg    subid
1   22  1.56  B14-112