[英]How to cut data from one column and paste into a new column in Python -> Pandas?
For example, I have the DataFrame:例如,我有数据帧:
import pandas as pd
a = [{'name': 'RealMadrid_RT'}, {'name': 'Bavaria_FD'}, {'name': 'Lion_NS'}]
df = pd.DataFrame(a)
I need to create new column -> df['name_2'], next, cut the data from column df['name'] and paste to column df['name_2'].我需要创建新列 -> df['name_2'],接下来,从列 df['name'] 中剪切数据并粘贴到列 df['name_2']。 I require getting the next result how on the screenshot
我需要在屏幕截图上如何获得下一个结果
I will be grateful for the answer我将不胜感激
This will work, assuming you don't want the underscore in the second column:这将起作用,假设您不希望在第二列中使用下划线:
df = df['name'].str.partition('_').drop(1, axis=1)
df.columns = ['name', 'name2']
Use str.extract
to get the expected outcome:使用
str.extract
获得预期结果:
# With underscore
>>> df['name'].str.extract('(.*)(_.*)').rename(columns={0: 'name', 1: 'name_2'})
name name_2
0 RealMadrid _RT
1 Bavaria _FD
2 Lion _NS
# Without underscore
>>> df['name'].str.extract('(.*)_(.*)').rename(columns={0: 'name', 1: 'name_2'})
name name_2
0 RealMadrid RT
1 Bavaria FD
2 Lion NS
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.