I have a dataframe
name g1 g2
a 1 1
a 0 na
a 1 3
b 1 na
b 2 na
b 3 4
c 4 na
I want to move g2 values to g1 without moving the na the returned columns should be
name g1 g2
a 1 1
a 0 na
a 3 3
b 1 na
b 2 na
b 4 4
c 4 na
I used df.replace(g1, g2),
but that will move the NA as well. Is there anyone to not move the NA
This is one approach:
data = [['a', '1', '1'], ['a', '0', np.nan], ['a', '1', '3'], ['b', '1', np.nan],
['b', '2', np.nan], ['b', '3', '4'], ['c', '4', np.nan]]
df = pd.DataFrame(data, columns=['name', 'g1', 'g2'])
df['g1'] = df['g2'].fillna(df['g1'])
print(df)
Output:
name g1 g2
0 a 1 1
1 a 0 NaN
2 a 3 3
3 b 1 NaN
4 b 2 NaN
5 b 4 4
6 c 4 NaN
您可以使用notna
检查:
df.loc[df['g2'].notna(), 'g1'] = df['g2']
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.