繁体   English   中英

Python数据框:根据特定条件合并列的值

[英]Python dataframes: Merge values of columns according to a specific condition

嗨,我有一个数据框问题。 可以说我有一个这样的数据框

label    value 
1        a
1        b 
2  
2 
1        c
1        d

所以现在我有了标签1的两个连续部分。 我想要这样的输出:

output: [ab,cd] 

不同区域的标签1的哪些相关值合并在一起。 谢谢。

您可以使用itertools.groupby ,它仅对相似的相邻项目进行分组:

from itertools import groupby
from operator import itemgetter

zipper = zip(df['label'], df['value'])
grouper = groupby(list(zipper), key=itemgetter(0))
res = [''.join(map(itemgetter(1), j)) for i, j in grouper if i == 1]

['ab', 'cd']

您可以尝试通过基于两个连续的标签“ 1”的条件对值中的value求和:

>> df['label'] = df['label'].astype(str)

>> res = df + df.shift(-1)

  label value
0    11    ab
1    12   NaN
2    22   NaN
3    21   NaN
4    11    cd
5   NaN   NaN

然后,我们在res过滤label匹配'11'的行:

>> res[res['label'].eq('11')]['value'].values.tolist()

['ab', 'cd']

您可以尝试

->按标签序列对数据框进行分组并添加分组的值

->按标签分组数据框以获取单个ID信息作为列表

考虑数据框

    label   value
0   1   a
1   1   b
2   2   NaN
3   2   NaN
4   1   c
5   1   d
6   1   e
7   3   b
8   3   c

#grouping the dataframe by label sequence checking with the previous value
df['value1'] = df.groupby(df.label.diff(1).abs().cumsum().fillna(0)).transform(sum)['value']

0    4.0
1    4.0
2    3.0
3    3.0
4    2.0
5    2.0
6    2.0
7    0.0
8    0.0

#group the dataframe by label to get individual ids information as list
df.groupby(df.label).apply(lambda x: x['value1'].unique())

出:

      label
1    [ab, cde]
2        [0.0]
3         [bc]
dtype: object

使用Pandas可以按label过滤数据框。 然后将GroupBy与使用cumsum构造的石斑鱼系列一起使用:

grouper = df['label'].ne(df['label'].shift()).cumsum()

res = df.loc[df['label'] == 1]\
        .groupby(grouper)['value'].sum().tolist()

['ab', 'cd']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM