Python检查多个列并比较字符串

2024-04-27 00:06:21 发布

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

假设下面有一个数据帧

       a        b        c
0    one      two    three
1  three      one      two

我想将第0行和第1行作为同一个列表处理?或者别的什么,因为两行都包含'one'、'two'、'three',尽管顺序不同

我应该创建一个新列来存储a,b,c列中的所有字符串吗

       a        b        c                d
0    one      two    three    one two three
1  three      one      two    three one two

然后比较d列的第0行和第1行

在这之后,我想做。groupby('d'),因此,'一二三'和'三一二'不能分开

我想不出解决这个问题的办法,需要帮助


Tags: 数据字符串列表顺序onethreegroupbytwo
2条回答

您创建的新列应该是tuple,因为列表是不可散列的(groupby将失败)。所以我们首先用tolist()创建列,然后对它进行排序,然后transform将它转换成tuple

设置

import pandas as pd

data = {'a': ['one', 'three'], 'b': ['two', 'one'], 'c': ['three', 'two']}
df = pd.DataFrame(data)

排序和转换…

df['d'] = df.values.tolist()
df['d'] = (    
     df['d'].transform(sorted)
         .transform(tuple)
)
print(df.groupby('d').sum()) # I'm calling sum() just to show groupby working 

# prints only one group:
#                           a       b         c
# d
# (one, three, two)  onethree  twoone  threetwo

在加入之前对每行中的单元格进行排序,以创建分组字符串

使用轴为1的应用程序按行应用此函数

df['d'] = df.apply(lambda x: ' '.join(x.sort_values()), axis=1)

# outputs:

       a    b      c              d
0    one  two  three  one three two
1  three  one    two  one three two

d分组将把两行放在同一个组中。示例:

df.groupby('d').agg('count')

               a  b  c
d
one three two  2  2  2

相关问题 更多 >