基于不同列操作数据帧

2024-10-06 07:47:30 发布

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

我有一个数据帧df,它有两列,分别是Rule\ ID和Location。它有如下数据-

Rule_ID                         Location
[u'2c78g',u'df567',u'5ty78']    US
[u'2c78g',u'd67gh',u'df890o']   India
[u'd67gh',u'df890o',u'5ty78']   Japan
[u'2c78g',u'5ty78',u'df890o']   US

我想要两个结果。每个位置的一个唯一规则ID计数。这里看起来应该是-

Location    Count_of_unique_rule_ids
US          4
India       3
Japan       3

其次,我要按位置计算规则ID。在这里它看起来像-

Rule_ID    Count   Location
u'2c78g'   2       US
u'df567'   1       US 
u'5ty78'   2       US

等等!你知道吗

这是问题的扩展-Manipulating data frames


Tags: of数据iddf规则countlocationrule
2条回答

您需要将数据帧转换为长格式(unnest columnRule\ID),然后直接进行总结:

df_long = pd.DataFrame({
        "Rule_ID": [e for s in df.Rule_ID for e in s],
        "Location": df.Location.repeat(df.Rule_ID.str.len())
    })

df_long.groupby('Location').Rule_ID.nunique()

#Location
#India    3
#Japan    3
#US       4
#Name: Rule_ID, dtype: int64

df_long.groupby(['Rule_ID', 'Location']).size()

#Rule_ID    Location
#u'2c78g'   India       1
#           US          2
#u'5ty78'   Japan       1
#           US          2
#u'd67gh'   India       1
#           Japan       1
#u'df567'   US          1
#u'df890o'  India       1
#           Japan       1
#           US          1
#dtype: int64

这里有一条路

使用apply

In [235]: df.groupby('Location')['Rule_ID'].apply(lambda x: len(set(x.sum())))
Out[235]:
Location
India    3
Japan    3
US       4
Name: Rule_ID, dtype: int64

-

In [236]: (df.groupby('Location')
             .apply(lambda x: pd.Series(x['Rule_ID'].sum()))
             .reset_index()
             .groupby(['Location', 0]).size())
Out[236]:
Location  0
India     2c78g     1
          d67gh     1
          df890o    1
Japan     5ty78     1
          d67gh     1
          df890o    1
US        2c78g     2
          5ty78     2
          df567     1
          df890o    1
dtype: int64

细节

x.sum()在链表连接它们时,可以通过对链表集合进行计数来获得唯一的计数。你知道吗

In [237]: df.groupby('Location')['Rule_ID'].apply(lambda x: x.sum())
Out[237]:
Location
India                         [2c78g, d67gh, df890o]
Japan                         [d67gh, df890o, 5ty78]
US       [2c78g, df567, 5ty78, 2c78g, 5ty78, df890o]
Name: Rule_ID, dtype: object

在列表上应用pd.Series将创建新行,然后在位置和度量上应用groupby。你知道吗

In [240]: df.groupby('Location').apply(lambda x: pd.Series(x['Rule_ID'].sum()))
Out[240]:
Location
India     0     2c78g
          1     d67gh
          2    df890o
Japan     0     d67gh
          1    df890o
          2     5ty78
US        0     2c78g
          1     df567
          2     5ty78
          3     2c78g
          4     5ty78
          5    df890o
dtype: object

相关问题 更多 >