Changing cell values to "Nan" based on partial string

Viewed 43

I have a data frame that looks something like this (although with more columns):

    import  external_no    heading1          heading2                           heading3
0   | 0 |   12731274    |Text: Moretext0    |NaN                                |NaN
...
5   |6  |   12731302    |Text: Moretext5    |Text: Moretext9--Evenmoretext1     |Text: Moretext12--Evenmoretext3
6   |7  |   12731303    |Text: Moretext6    |Text: Moretext10--Evenmoretext2    |Text: Moretext13--Evenmoretext4
7   |8  |   12719851    |Text: Moretext7    |Text: Moretext11                   |Text: Moretext14

What I want to do is change any of the cells that contain the bit of text "--" to NaN and then save that as a new dataframe.

The first 2 columns are integers(I think) and the rest are text, so that may be part of the problem.

I tried this:

df2=df.iloc[:, 2:].mask(df.iloc[:, 2:].str.contains("--"))

and get this error:

'DataFrame' object has no attribute 'str'. Did you mean: 'std'?
1 Answers

This may work:

df2 = df[["col_name1", "col_name2"]]

columns = df.columns[2:]

for col in columns:
    df2[col] = df.apply(lambda x: np.nan if "--" in x[col] else x[col], axis=1)
Related