简体   繁体   English

如果列以字符串的一部分开头,Pandas 将替换并填充

[英]Pandas replace and fillna if column begins with part of a string

I was wondering whether there is a way to use the .replace() and .fillna() for columns headers that begin with part of a string.我想知道是否有一种方法可以将 .replace() 和 .fillna() 用于以字符串的一部分开头的列标题。

For example:例如:

data['Q5_A'].fillna(value='Not Applicable', inplace=True)

This will only apply .fillna() to column Q5_A.这只会将 .fillna() 应用于 Q5_A 列。

Similarily:同样:

data["Q5_S"] = data["Q5_S"].replace(",", "", regex=True)

This will only apply .replace() to column Q5_S.这只会将 .replace() 应用于 Q5_S 列。

What if I would like it to apply to any columns that have "Q5_" in the header?如果我希望它应用于标题中包含“Q5_”的任何列怎么办?

Thanks!谢谢!

Filter the required columns then do replace/fillna: Filter所需的列,然后替换/填充:

data.assign(**data.filter(like='Q5_').replace(",", "", regex=True))

Alternatively, if you want to modify the dataframe inplace, we can do:或者,如果您想就地修改数据框,我们可以这样做:

cols = data.filter(like='Q5_').columns
data[cols] = data[cols].replace(",", "", regex=True)

You can do a for loop and perform all the processes you need as well.您也可以执行 for 循环并执行您需要的所有过程。

for header in data.columns:
    if "Q5" in header:
        data[header].fillna(value='Not Applicable', inplace=True)
        data[header] = data[header].replace(",", "", regex=True)

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

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