简体   繁体   English

将功能应用于数据框中的特定行

[英]Apply function to specific row in dataframe

I have a dataframe of which I want to clean up a specific row, in this case the first row. 我有一个要清理特定行的数据框,在本例中为第一行。 I have written a function in which I believe will return the string if the regex is matched. 我编写了一个函数,如果正则表达式匹配,我相信该函数将返回字符串。

def clean_cells(string):
    if '201' in string:
        return re.findall('201[0-9]', string)[0]
    else:
        return string

I want to apply this function to the first row in the dataframe then replace the first row with the cleaned up version then contatenate the rest of the original dataframe. 我想将此功能应用于数据框的第一行,然后将第一行替换为清理后的版本,然后处理原始数据框的其余部分。

I have tried: 我试过了:

df = df.iloc[[0]].apply(clean_cells)

Select first row by position and all columns with : and assign back: 按位置选择第一行,并使用:选择所有列,然后分配:

df.iloc[0, :] = df.iloc[0, :].apply(clean_cells)

Another solution: 另一个解决方案:

df.iloc[0] = df.iloc[0].apply(clean_cells)

仅替换选定的行,而不是整个DataFrame:

df.iloc[[0]] = df.iloc[[0]].apply(clean_cells)

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

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