删除d的同一单元格中的重复值和计数值

2024-05-20 17:10:39 发布

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

我有一个示例Dataframe,列a包含如下重复值:

        a
0   1089, 1089, 1089
1   10A3, 10A3
2   10A3, 10A4, 10A4
3   TEL, TV
4   EZ, EZ
5   ABC Co., ABC Co.

我要删除重复项并计算每个单元格的值:

      a               count
0   1089                1
1   10A3                1
2   10A3, 10A4          2
3   TEL, TV             2
4   EZ                  1
5   ABC Co.             1

Tags: 示例dataframecounttvabccotelez
3条回答

试试这个


def f(x):

    l = x.split(',')

    d = {}

    for key in l:
        if key.rstrip() not in d:
            d[key.rstrip()] = 0
        d[key.rstrip()]+=1

    return ','.join(list(d.keys()))
df['a_new'] = df['a'].apply(lambda x:f(x))
print(df)
df['count'] = df['a_new'].apply(lambda x: len(x.split(',')))

使用^{}并跨axis=1求和

df['count'] = df.a.str.get_dummies(sep=', ').sum(1)

要删除重复项,请使用explode

s = df.assign(a=df.a.str.split(', ')).explode('a').drop_duplicates()

         a  count
0     1089      1
1     10A3      1
2     10A3      2
2     10A4      2
3      TEL      2
3       TV      2
4       EZ      1
5  ABC Co.      1

如果你真的需要它在同一行。。。你知道吗

s.groupby(s.index).agg({'a': ', '.join, 'count': 'first'})

          a  count
0        1089      1
1        10A3      1
2  10A3, 10A4      2
3     TEL, TV      2
4          EZ      1
5     ABC Co.      1

或者干脆用@WeNYoBen巧妙的解决方案;)

s=df.a.str.get_dummies(sep=', ')
df['a']=s.dot(s.columns+',').str[:-1]
df['count']=s.sum(1)

您需要定义自己的方法并将其应用于数据帧。你知道吗

def list_count(x):
    l=pd.Series(x.split(',')).str.strip().drop_duplicates().tolist()
    return pd.Series([', '.join(l), len(l)])

df['a'].apply(lambda x: list_count(x)).rename(columns={0:'a', 1:'count'})

输出:

            a  count
0        1089      1
1        10A3      1
2  10A3, 10A4      2
3     TEL, TV      2
4          EZ      1
5     ABC Co.      1

相关问题 更多 >