简体   繁体   English

如何从一列中剪切数据并粘贴到 Python -> Pandas 中的新列中?

[英]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.

相关问题 从列中删除单词并粘贴到新列 - Cut word from column and paste to new column 如何将特定数据从一列移动到 Pandas 上的新列? - How to move specific data from one column to a new column on Pandas? pandas:如何按一列排序并按另一列切割 - pandas: how to sort by one column and cut by another 如何通过 pandas 将特定列从一个 df 复制/粘贴到另一个 - How to copy/paste particular column from one df to another by pandas pandas中如何动态截取两列过滤后的数据粘贴到新列中 - How to dynamically cut filtered data from two columns and paste them into new columns in pandas python pandas-如何合并日期和另一列的时间并创建新列 - python pandas - how to merge date from one and time from another column and create new column 如何在python中切割一个pandas列,并使另一列长度相等? - How to cut one pandas column in python, and make the other column equal in length? 搜索列,如果值不是所有数字,则将值剪切并粘贴到同一行的另一列 python pandas - Search column, if value is not all digits, then cut&paste value to another column same row python pandas 如何从一列中提取信息以在熊猫数据框中创建新列 - How to extract information from one column to create a new column in a pandas data frame 将一列与另一数据框列匹配并粘贴第二个数据中的值 - Python - Match one column with another data frame column and paste value from second data - Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM