I have a DataFrame with 2 columns.
col_1 | col_2 |
---|---|
apple | NaN |
pear | NaN |
mango | NaN |
NaN | Strawberry |
I want to check col_2 for NaN, If the value is not NULL or NaN copy value of col_2 to col_1.
df = {'col_1': ['apple', 'pear', 'mango',''],
'col_2': [Nan,Nan,Nan,'Strawberry' ]}
print(df)
for idx, row in df.iterrows():
if df.loc[idx, col_2].notna:
print("inside if")
else:
print("inside else")
every time it goes in if and never goes in else.
CodePudding user response:
I think this will solve your problem, which says to copy non-NaN values from col_2 to col_1. Since that's a rather unusual operation, I'm uncertain whether you meant to do that or maybe meant copy values from col1 to col2.
Nan = np.nan
df = pd.DataFrame({'col_1': ['apple', 'pear', 'mango',''],
'col_2': [Nan,Nan,Nan,'Strawberry' ]})
df.col_1.mask(df.col_2.notna(), df.col_2)
CodePudding user response:
Backfill values from col_2
to col_1
.
Given:
col_1 col_2
0 apple NaN
1 pear NaN
2 mango NaN
3 NaN Strawberry
Doing:
df = df.bfill(axis=1)
print(df)
Output:
col_1 col_2
0 apple NaN
1 pear NaN
2 mango NaN
3 Strawberry Strawberry
CodePudding user response:
This solved the issue.
df['col_2'].fillna("", inplace = True)