import pandas as pd
from IPython.core.display import display
data={'name':['张三','李四','王五','小明'],'sex':['female','female','male','male'],
'year':[2001,2001,2003,2004],'city':['北京','上海','广州','北京']}
df1=pd.DataFrame(data,columns=['name','sex','year','city'])
df3=df1.set_index(['sex','city'])
df3=df3.reset_index(['sex'])
print(df3)
data1={'year':2001,'name':'lanlan','sex':'male','city':'北京'}
df4=df3.append(data1,ignore_index=True)
print(df4)
结果:
sex name year
city
北京 female 张三 2001
上海 female 李四 2001
广州 male 王五 2003
北京 male 小明 2004
sex name year city
0 female 张三 2001 NaN
1 female 李四 2001 NaN
2 male 王五 2003 NaN
3 male 小明 2004 NaN
4 male lanlan 2001 北京
Process finished with exit code 0
import pandas as pd
from IPython.core.display import display
data={'name':['张三','李四','王五','小明'],'sex':['female','female','male','male'],
'year':[2001,2001,2003,2004],'city':['北京','上海','广州','北京']}
df1=pd.DataFrame(data,columns=['name','sex','year','city'])
print(df1)
data1={'year':2001,'name':'lanlan','sex':'male','city':'北京'}
df4=df1.append(data1,ignore_index=True)
print(df4)
结果:
name sex year city
0 张三 female 2001 北京
1 李四 female 2001 上海
2 王五 male 2003 广州
3 小明 male 2004 北京
name sex year city
0 张三 female 2001 北京
1 李四 female 2001 上海
2 王五 male 2003 广州
3 小明 male 2004 北京
4 lanlan male 2001 北京
Process finished with exit code 0