在pandas DataFrame元素中拆分字符串并重新组合列表的一部分

时间:2018-01-08 11:16:15

标签: python pandas dataframe

我试图找出如何在pandas元素中拆分字符串,然后重新组合拆分字符串的一部分。我有以下代码:

import pandas as pd

df = pd.DataFrame({'code': ['PC001-S002_D_CFI4-1_NN','PC001-S002_D_CFI4-1_NN','PC001-S002_D_CFI4-1_NN',
                            'PC001-S002_D_CFI4-1_ER','PC001-S002_D_CFI4-1_ER','PC001-S002_D_CFI4-1_ER']})

df['domain'] = df['code'].str.split("_")

此代码适用于在下划线上拆分字符串。现在,我想在列中获取生成的拆分列表,并重新组合前三个元素,以便:

PC001-S001_D_CFI4-1_NN ==>的 PC001-S001_D_CFI4-1

如果我只是使用:

申请字符串,我可以这样做
a = 'PC001-S002_D_CFI4-1_NN'
b = a.split("_")[0:3]
c = "_".join(b)

然而,我试图将此应用于熊猫而没有太大成功。

任何建议都会得到很好的接受。

2 个答案:

答案 0 :(得分:4)

您可以使用Series.str.rsplit(...)

In [11]: df['domain'] = df['code'].str.rsplit('_',1).str[0]

In [12]: df
Out[12]:
                     code               domain
0  PC001-S002_D_CFI4-1_NN  PC001-S002_D_CFI4-1
1  PC001-S002_D_CFI4-1_NN  PC001-S002_D_CFI4-1
2  PC001-S002_D_CFI4-1_NN  PC001-S002_D_CFI4-1
3  PC001-S002_D_CFI4-1_ER  PC001-S002_D_CFI4-1
4  PC001-S002_D_CFI4-1_ER  PC001-S002_D_CFI4-1
5  PC001-S002_D_CFI4-1_ER  PC001-S002_D_CFI4-1

或者只删除最后一部分:

In [7]: df['domain'] = df['code'].str.replace(r'\_\w+?$','')

In [8]: df
Out[8]:
                     code               domain
0  PC001-S002_D_CFI4-1_NN  PC001-S002_D_CFI4-1
1  PC001-S002_D_CFI4-1_NN  PC001-S002_D_CFI4-1
2  PC001-S002_D_CFI4-1_NN  PC001-S002_D_CFI4-1
3  PC001-S002_D_CFI4-1_ER  PC001-S002_D_CFI4-1
4  PC001-S002_D_CFI4-1_ER  PC001-S002_D_CFI4-1
5  PC001-S002_D_CFI4-1_ER  PC001-S002_D_CFI4-1

答案 1 :(得分:3)

使用str[:3]选择前3 list,然后join

df['domain'] = df['code'].str.split("_").str[:3].str.join('_')
print (df)

                     code               domain
0  PC001-S002_D_CFI4-1_NN  PC001-S002_D_CFI4-1
1  PC001-S002_D_CFI4-1_NN  PC001-S002_D_CFI4-1
2  PC001-S002_D_CFI4-1_NN  PC001-S002_D_CFI4-1
3  PC001-S002_D_CFI4-1_ER  PC001-S002_D_CFI4-1
4  PC001-S002_D_CFI4-1_ER  PC001-S002_D_CFI4-1
5  PC001-S002_D_CFI4-1_ER  PC001-S002_D_CFI4-1