简体   繁体   English

将 python pandas 中的列拆分为两列

[英]Split column in python pandas into two columns

I want to split the entry (always a string containing 6 letters) of a column 'Compared Image Type' of a pandas dataframe into two new columns of which one contains the first three letters, the other contains the last three letters of the original column.我想将 pandas 数据帧的“比较图像类型”列的条目(始终包含 6 个字母的字符串)拆分为两个新列,其中一个包含前三个字母,另一个包含原始列的最后三个字母.

Name    BaseImage Type  Compared Image Type
 2       oldNeg             semNeg
 2       oldNeu             perNeu
 2       oldNeu             semNeu
 2       oldNeu             newNeu
 2       oldNeg             perNeg

So far I've only found out how to split a column after a certain character (eg after a ",") and would be thankful for any help.到目前为止,我只发现了如何在某个字符之后(例如在“,”之后)拆分列,并感谢您的帮助。

You have str access:您有str访问权限:

df['col1'] = df['Compared Image Type'].str[:3]
df['col2'] = df['Compared Image Type'].str[3:]

OUtput:输出:

   Name BaseImage Type Compared Image Type col1 col2
0     2         oldNeg              semNeg  sem  Neg
1     2         oldNeu              perNeu  per  Neu
2     2         oldNeu              semNeu  sem  Neu
3     2         oldNeu              newNeu  new  Neu
4     2         oldNeg              perNeg  per  Neg

Based on your data, you can also use a similar approach to split a column using certain character, here capital letters [AZ] :根据您的数据,您还可以使用类似的方法使用特定字符拆分列,这里是大写字母[AZ]

df['Compared Image Type'].str.extract('^(\w*)([A-Z]\w*)')

Output:输出:

     0    1
0  sem  Neg
1  per  Neu
2  sem  Neu
3  new  Neu
4  per  Neg

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM