简体   繁体   English

Python Pandas从部分字符串匹配中填充列

[英]Python Pandas populate column from partial string match

I have a dataframe like below, and I need to create a new column Block with either the value 1 or 2 in it based on a partial string match in the column Program Number where it says _block_1 or _block_2. 我有一个如下所示的数据Block ,我需要根据“ Program Number ”列中表示“ _block_1”或“ _block_2”的部分字符串匹配,在其中创建一个新列“ Block ,其值为12 I've been trying if statements and .str.contains but can't get it to work. 我一直在尝试如果语句和.str.contains但不能使其正常工作。 How would you do this? 你会怎么做?

148 0209-3SP_block_1    ['g76p010060q00250r.0005'   'JEBD0507160 REV A' CHNCIII
149 0209-3SP_block_2    ['g76x.3761z-.500p03067q03067f.05'  'JEBD0507160 REV A' CHNC III
150 0209-5SP_block_1    ['g76p020060q00250r.0005'   'JEBD0507160 REV A' CHNC III
151 0209-5SP_block_2    ['g76x.3767z-.48p03067q03067f.05'   'JEBD0507160 REV A' CHNC III
152 0210-3SP_block_1    ['g76p010060q00250r.0005'   'JEBD0507160 REV A' CHNC III

You could use the method where from numpy : 您可以使用numpy where方法:

import numpy as np

df['Block'] = np.where(
    df['Machine'].str.contains('_block_1'),1,
    np.where(df['Machine'].str.contains('_block_2'),2,0)
)

Otherwise, assuming all the strings have the same length: 否则,假设所有字符串具有相同的长度:

df['Block'] = df['Machine'].str[15:].astype(int)

暂无
暂无

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

相关问题 使用 python/pandas 从另一个 excel 列中的一个 excel 列中查找部分字符串匹配 - Find a partial string match from one excel column in another excel column using python/pandas Python Pandas部分字符串匹配 - python pandas partial string match 从列表中的数据框列中搜索部分字符串匹配 - Pandas - Python - Search for a partial string match in a data frame column from a list - Pandas - Python Python Pandas dataframe中的字符串列表部分匹配 - Python Pandas partial match of list of string in dataframe 如果同一 pandas 列中的部分字符串匹配,则更新另一列中的值 - If partial string in the same pandas column match then update the value in another column Pandas 通过部分字符串匹配大小将列分配给数组维度错误 - Pandas Assign column by partial string match size to array dimension error pandas - 如果存在部分字符串匹配,则将值放入新列 - pandas - If partial string match exists, put value in new column 如何根据部分字符串匹配添加 pandas 列? - How to add a pandas column based on partial string match? 当我尝试从 python 中的 Pandas 数据框创建新列时,部分关键字匹配不起作用? - Partial keyword match not working when I am trying to create a new column from a pandas data frame in python? Python:熊猫列中的部分字符串匹配并从熊猫数据框中的其他列中检索值 - Python: Partial String matching in pandas column and retrieve the values from other columns in pandas dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM