The following is a sub-set of data frame:
id words A B C D E
1 new 1 1
2 good 1
3 star 1
4 never
5 final
I want to define a new variable (called FF) as a new column and assign 1 to it, if values for all other variables (columns) are "null". The new data frame would be like this:
id words A B C D E FF
1 new 1 1
2 good 1
3 star 1
4 never 1
5 final 1
How I can do it using python and Pandas ? Thanks.
You can define a function that is applied row-wise to the data frame:
def fill_if_nan(row):
if row[['A', 'B', 'C', 'D', 'E']].isnull().all():
return 1
return None
df['FF'] = df.apply(fill_if_nan, axis=1)
Or a more elegant numpy based solution:
df['FF'] = np.where(df[['A', 'B', 'C', 'D', 'E']].isnull().all(1), 1, np.nan)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.