Pandas:根据nam中的分隔符拆分多值列

2024-05-16 23:46:34 发布

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

我有一个大熊猫数据帧,其中有许多多值列。这些列的名称中有“/”,这些列中的值也用“/”分隔。下面是这种数据帧的最小代表性示例。在

        Name   North / South   East / West   No1 / No2 / No3
0        ABC           0 / 1         0 / 0        10 / 3 / 6
1        XYZ           1 / 0         0 / 1         4 / 5 / 6
2        PQR           1 / 0         0 / 1         3 / 6 / 6

我想把这些列分开。简单的方法是创建一个新的列,然后沿着索引的长度进行迭代,在索引中填充每个元素的拆分字符串。但我必须对所有多值列进行硬编码。在

有没有更普遍的方法?或许可以浏览一下数据框列如果一个元素中包含“/”,那么运行另一个函数来分解该列?对于上述数据帧,所需的输出如下所示。在

^{pr2}$

Tags: 数据方法name名称元素示例westsouth
2条回答

这里有一种方法

In [1417]: pd.concat([s.str.split(' / ').apply(pd.Series, index=c.split(' / ')) 
                     for c, s in df.set_index('Name').iteritems()],
                     axis=1).reset_index()
Out[1417]:
  Name North South East West No1 No2 No3
0  ABC     0     1    0    0  10   3   6
1  XYZ     1     0    0    1   4   5   6
2  PQR     1     0    0    1   3   6   6
#get columns not contains / and set index
cols = df.columns[~df.columns.str.contains('/')].tolist()
df = df.set_index(cols)
print (df)
     North / South East / West No1 / No2 / No3
Name                                          
ABC          0 / 1       0 / 0      10 / 3 / 6
XYZ          1 / 0       0 / 1       4 / 5 / 6
PQR          1 / 0       0 / 1       3 / 6 / 6

#create new columns names
c = df.columns.to_series().str.split(' / ', expand=True).stack().values.tolist()
print (c)
['North', 'South', 'East', 'West', 'No1', 'No2', 'No3']

#list comprehension with split to df and concat output
df = pd.concat([df[x].str.split(' / ', expand=True) for x in df], axis=1)
print (df)
      0  1  0  1   0  1  2
Name                      
ABC   0  1  0  0  10  3  6
XYZ   1  0  0  1   4  5  6
PQR   1  0  0  1   3  6  6

#assign new columns names
df.columns = c
df = df.reset_index()
print (df)
  Name North South East West No1 No2 No3
0  ABC     0     1    0    0  10   3   6
1  XYZ     1     0    0    1   4   5   6
2  PQR     1     0    0    1   3   6   6

计时

^{pr2}$

相关问题 更多 >