Python 使用Pandas替换不同列的元素
我有两个数据帧列,如下所示:Python 使用Pandas替换不同列的元素,python,pandas,dataframe,alternate,Python,Pandas,Dataframe,Alternate,我有两个数据帧列,如下所示: df1 = pd.DataFrame({'A':['CINO','KONO','ROLO','MANE','TUTU']}) df2 = pd.DataFrame({'B':['NION','PONO','RZCO','MPPE','TQAS']}) C CC1 CINO <---- belongs to A CC1 NION <---- belongs to B CC2 KONO <---- belongs to
df1 = pd.DataFrame({'A':['CINO','KONO','ROLO','MANE','TUTU']})
df2 = pd.DataFrame({'B':['NION','PONO','RZCO','MPPE','TQAS']})
C
CC1 CINO <---- belongs to A
CC1 NION <---- belongs to B
CC2 KONO <---- belongs to A
CC2 PONO <---- belongs to B
CC3 ROLO <---- belongs to A
CC3 RZCO <---- belongs to B
CC4 MANE <---- belongs to A
CC4 MPPE <---- belongs to B
CC5 TUTU <---- belongs to A
CC5 TQAS <---- belongs to B
我的想法是以如下方式组合数据帧:
df1 = pd.DataFrame({'A':['CINO','KONO','ROLO','MANE','TUTU']})
df2 = pd.DataFrame({'B':['NION','PONO','RZCO','MPPE','TQAS']})
C
CC1 CINO <---- belongs to A
CC1 NION <---- belongs to B
CC2 KONO <---- belongs to A
CC2 PONO <---- belongs to B
CC3 ROLO <---- belongs to A
CC3 RZCO <---- belongs to B
CC4 MANE <---- belongs to A
CC4 MPPE <---- belongs to B
CC5 TUTU <---- belongs to A
CC5 TQAS <---- belongs to B
如您所见,B列的项目位于A列的行之间。
注意行的命名方式,每对行都有相同的名称
你能给我推荐一个使用一些内置功能实现这一目标的聪明方法吗?你可以使用:
pd.concat(
[df1, df2], axis=1
).stack().reset_index(1, drop=True).to_frame('C').rename(index='CC{}'.format)
C
CC0 CINO
CC0 NION
CC1 KONO
CC1 PONO
CC2 ROLO
CC2 RZCO
CC3 MANE
CC3 MPPE
CC4 TUTU
CC4 TQAS
df = pd.concat([df1.rename(columns={'A':'C'}),
df2.rename(columns={'B':'C'})], keys=[1,2])
.sort_index(level=[1,0])
.reset_index(level=0, drop=True)
df.index = 'CC' + df.index.astype(str)
print (df)
C
CC0 CINO
CC0 NION
CC1 KONO
CC1 PONO
CC2 ROLO
CC2 RZCO
CC3 MANE
CC3 MPPE
CC4 TUTU
CC4 TQAS
您可以使用:
df = pd.concat([df1.rename(columns={'A':'C'}),
df2.rename(columns={'B':'C'})], keys=[1,2])
.sort_index(level=[1,0])
.reset_index(level=0, drop=True)
df.index = 'CC' + df.index.astype(str)
print (df)
C
CC0 CINO
CC0 NION
CC1 KONO
CC1 PONO
CC2 ROLO
CC2 RZCO
CC3 MANE
CC3 MPPE
CC4 TUTU
CC4 TQAS