我有一个如下数据框:
data = [['lynda', 10,'F',125,'5/21/2018'],['tom', np.nan,'M',135,'7/21/2018'], ['nick', 15,'F',99,'6/21/2018'], ['juli', 14,np.nan,120,'1/21/2018'],['juli', 19,np.nan,140,'10/21/2018'],['juli', 18,np.nan,170,'9/21/2018']]
df = pd.DataFrame(data, columns = ['Name', 'Age','Gender','Height','Date'])
df
如何基于性别的np.NaN值转换数据框?
我希望将原始数据帧df拆分为df1(Name,Age,Gender,Height,Date),其值将为gender(df的前三行)
然后将其插入没有性别列(df的后三行)的df2(名称,年龄,高度,日期)
答案 0 :(得分:2)
这是一种方法:
import pandas as pd
import numpy as np
data = [['lynda', 10,'F',125,'5/21/2018'],['tom', np.nan,'M',135,'7/21/2018'], ['nick', 15,'F',99,'6/21/2018'], ['juli', 14,np.nan,120,'1/21/2018'],['juli', 19,np.nan,140,'10/21/2018'],['juli', 18,np.nan,170,'9/21/2018']]
df = pd.DataFrame(data, columns = ['Name', 'Age','Gender','Height','Date'])
df2 = df[df['Gender'].notnull()].drop("Gender", axis=1)
print(df2)
输出:
Name Age Height Date
0 lynda 10.0 125 5/21/2018
1 tom NaN 135 7/21/2018
2 nick 15.0 99 6/21/2018