通过定界符在Pandas中拆分列的值而不会丢失定界符 [英] Splitting Columns' Values in Pandas by delimiter without losing delimiter
问题描述
我有一个遵循以下格式的数据框:
Hi I have a dataframe that follows this format:
df = pd.DataFrame(np.array([[1, 2, 'Apples 20pk ABC123', 4, 5], [6, 7,
'Oranges 40pk XYZ123', 9, 0], [5, 6, 'Bananas 20pk ABC123', 8, 9]]), columns=
['Serial #', 'Branch ID', 'Info', 'Value1', 'Value2'])
Serial# Branch ID Info Value1 Value2
0 1 2 Apples 20pk ABC123 4 5
1 6 7 Bananas 20pk ABC123 9 0
2 5 6 Oranges 40pk XYZ123 8 9
我想基于"pk"字符拆分信息"列的值.本质上,我想创建两个新列,如下面的数据框所示:
I want to split the "Info" column's values based on the "pk" character. Essentially, I want to create two new columns, like in the dataframe below:
Serial# Branch ID Package Branch Value1 Value2
0 1 2 Apples 20pk ABC123 4 5
1 6 7 Bananas 20pk ABC123 9 0
2 5 6 Oranges 40pk XYZ123 8 9
我尝试使用:
info = df["Info"].str.split("pk ", n=1, expand=True)
df['Package'] = branch[0]
df['Branch'] = branch[1]
del df['Info']
但是结果是,在df的包装"列中,我只获得了"Apples 20",而不是"Apples 20pk".
but the result is that in df's column, 'Package', I only get "Apples 20" instead of "Apples 20pk".
我想使用"字符(一个空格)进行分割,但是我得到了三个值('Apples','20pk','ABC123').
I wanted to split using the " " character (a space) but, then I get three values ('Apples', '20pk', 'ABC123').
因为有n行(而不仅仅是3行),所以我想知道最有效的方法是什么?谢谢!
Because there are n number of rows (not just 3), I was wondering what's the most efficient way to go about this? Thanks!
推荐答案
我们可以在此处使用正向表达式使用正则表达式.在这种情况下,我们在空格( \ s
)上分割,该空格前面(?< =
)的字符串是 pk
:
We can use regular expression here with positive lookbehind. In this case we split on a whitespace (\s
) which is preceded (?<=
) by the string pk
:
df['Info'].str.split('(?<=pk)\s', expand=True)
0 1
0 Apples 20pk ABC123
1 Oranges 40pk XYZ123
2 Bananas 20pk ABC123
为了获得您期望的输出,我们一次性创建了两列,然后放置 Info
:
To get your expected output, we create the two columns in one go and drop Info
afterwards:
df[['Package', 'Branch']] = df['Info'].str.split('(?<=pk)\s', expand=True)
df.drop('Info', axis=1, inplace=True)
Serial # Branch ID Value1 Value2 Package Branch
0 1 2 4 5 Apples 20pk ABC123
1 6 7 9 0 Oranges 40pk XYZ123
2 5 6 8 9 Bananas 20pk ABC123
这篇关于通过定界符在Pandas中拆分列的值而不会丢失定界符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!