Python:Pandas - 根据列值分隔数据框

标签 python pandas

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

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

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

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

   df2:

           age   fdg    subid
        1   22  1.56  B14-112

我怎样才能做到这一点?

最佳答案

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

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

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

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

我们还可以获得唯一值并再次使用它来过滤 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

关于Python:Pandas - 根据列值分隔数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27900733/

相关文章:

python - 使用 Pandas,如何将行值拆分为单独的列,并使用它们的值?

python - Pandas 的多种情况

python - Pandas 分组仅包含正值

python - 在另一个 1d/2d 向量之后重采样(缩小)2D 向量

python - 将数据框列中的字符串映射到数值

python - 如何在 cython 结构中创建日期时间字段?字符串字段怎么样?

python - numpy.exp() 溢出

python - ConfigObj 'un-nest' 部分

python - 使用假设重复条目的 Pandas Index 示例

python - 将 Html 页面中的数据获取到 Python 数组中