Pandas:如何在Pandas的DataFram中聚合*一些*列

2024-04-25 05:03:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将Pandas数据帧中的列聚合为一个,给定一定的条件。这样做的目的是节省DF中的空间,并将一些列聚合为一个列,前提是它们满足一定的条件。 举个例子可能更容易解释:

import pandas as pd
import seaborn as sns     # for sample data set

# load some sample data
titanic = sns.load_dataset('titanic')

# round the age to an integer for convenience
titanic['age_round'] = titanic['age'].round(0)

# crosstabulate
crtb = pd.crosstab(titanic['embark_town'], titanic['age_round'], margins=True)
crtb

产量:

enter image description here

例如,我要做的是将所有大于等于20的列(例如)聚合到一个名为“20+”的列中,这些值将是聚合列的每行所有值的总和。当列标题为<;20时,它们将保持分离且不受影响。 一种方法是在原始数据框中创建另一列,如果年龄的原始值为<;20和'20+,则将其舍入,或者使用.cut,并以此为中心。在

想知道是否有一种方法可以在不创建新专栏的情况下更巧妙地完成这项工作。 谢谢!在


Tags: sample方法importltforagedataas
1条回答
网友
1楼 · 发布于 2024-04-25 05:03:14

对于这个特定的示例,我认为您不需要添加列,只需更新现有列中的值:

import pandas as pd
import seaborn as sns     # for sample data set

# load some sample data
titanic = sns.load_dataset('titanic')

# round the age to an integer for convenience
titanic['age_round'] = titanic['age'].round(0)
titanic.loc[titanic['age_round']>=20, 'age_round'] = '20+'

# crosstabulate
crtb = pd.crosstab(titanic['embark_town'], titanic['age_round'], margins=True)

你的问题是一般怎么做吗?在pandas中聚合数据有许多不同的方法,最标准的是使用一个.groupby()构造。交叉表基本上是按这两个变量分组,然后调用.unstack()的快捷方式。在

相关问题 更多 >