简体   繁体   English

使用字符串值进行数据帧切片

[英]Dataframe slicing with string values

I have a string dataframe that I would like to modify.我有一个要修改的字符串数据框。 I need to cut off each row of the dataframe at a value say A4 and replace other values after A4 with -- or remove them.我需要在一个值(比如 A4)处切断数据帧的每一行,并用 -- 或删除它们来替换 A4 之后的其他值。 I would like to create a new dataframe that has values only upto the string "A4".我想创建一个新的数据框,它的值只能达到字符串“A4”。 How would i do this?我该怎么做?

import pandas as pd
columns = ['c1','c2','c3','c4','c5','c6']
values = [['A1', 'A2','A3','A4','A5','A6'],['A1','A3','A2','A5','A4','A6'],['A1','A2','A4','A3','A6','A5'],['A2','A1','A3','A4','A5','A6'], ['A2','A1','A3','A4','A6','A5'],['A1','A2','A4','A3','A5','A6']]
input = pd.DataFrame(values, columns)

columns = ['c1','c2','c3','c4','c5','c6']
values = [['A1', 'A2','A3','A4','--','--'],['A1','A3,'A2','A5','A4','--'],['A1','A2','A4','--','--','--'],['A2','A1','A3','A4','--','--'], ['A2','A1','A3','A4','--','--'],['A1','A2','A4','--','--','--']]
output =  pd.DataFrame(values, columns)

You can make a small function, that will take an array, and modify the values after your desired value:您可以创建一个小函数,它将采用一个数组,并在您想要的值之后修改值:

def myfunc(x, val):
    for i in range(len(x)):
        if x[i] == val:
            break
    x[(i+1):] = '--'
    return x

Then you need to apply the function to the dataframe in a rowwise ( axis = 1 ) manner:然后,你需要apply所述函数应用于所述数据帧在一个横行( axis = 1 )的方式:

input.apply(lambda x: myfunc(x, 'A4'), axis = 1)


0   1   2   3   4   5
c1  A1  A2  A3  A4  --  --
c2  A1  A3  A2  A5  A4  --
c3  A1  A2  A4  --  --  --
c4  A2  A1  A3  A5  A4  --
c5  A2  A1  A4  --  --  --
c6  A1  A2  A4  --  --  --

I assume you will have values more than A4我假设您的价值将超过A4

df.replace('A([5-9])', '--', regex=True)

     0   1   2   3   4   5
c1  A1  A2  A3  A4  --  --
c2  A1  A3  A2  --  A4  --
c3  A1  A2  A4  A3  --  --
c4  A2  A1  A3  --  A4  --
c5  A2  A1  A4  A3  --  --
c6  A1  A2  A4  A3  --  --

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

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