使用 Pandas 替换不同列的元素
Alternate elements of different columns using Pandas
我有 2 个这样的数据框列:
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
列的行之间。
请注意行的命名方式,即每对行都具有相同的名称。
你能建议我使用一些内置 Pandas 函数来实现这个目标的聪明方法吗?
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
我有 2 个这样的数据框列:
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
列的行之间。
请注意行的命名方式,即每对行都具有相同的名称。
你能建议我使用一些内置 Pandas 函数来实现这个目标的聪明方法吗?
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