Carlo Allocca
Carlo Allocca

Reputation: 651

Python pandas: How to select the first not "None" value from a specif column?

I would like fill a specif column of a dataset with the first not None value. For example, given the df:

col_name
None
None
A
A
B
B

output should be:

col_name
A
A
A
A
B
B

Any help on this, would be very appreciated. Thanks in advance. Carlo

Upvotes: 0

Views: 154

Answers (2)

piRSquared
piRSquared

Reputation: 294488

df.update(df.col_name.iloc[:df.col_name.notnull().argmax() + 1].bfill())

df

  col_name
0        A
1        A
2        A
3        A
4        B
5        B

Same Idea, but different

i = df.col_name.notnull().argmax()
df.col_name.values[:i] = df.col_name.values[i]

If None values are actually strings as in 'None'

i = df.col_name.ne('None').argmax()
df.col_name.iloc[:i] = df.col_name.iloc[i]

Upvotes: 2

Justin Scott
Justin Scott

Reputation: 51

You can convert the value to a numpy array by the dataframe.values variable, and then loop through it, comparing to numpy.nan, setting the value when true

eg.

colName = df['col_name'].values

colName[numpy.isnan(colName)] = 'A'

Upvotes: 0

Related Questions