将一个数据框的多列的值复制到另一个数据框的1列中

时间:2020-08-18 12:16:41

标签: python pandas

    ID  a1 a2 b1 b2
    1   
    2
    3
    4
    ... 
    300

我想创建一个新的数据框,合并列a1 a2和b1,b2。目的是获得这样的东西:

     ID  a  b 
     1   
     2
     3
     4
     ... 
     600

其中a基本上由两个列a1,a2依次给出。 有什么建议吗?

2 个答案:

答案 0 :(得分:1)

它确实有效,但是我想知道是否有更快的解决方案。这是代码:

df1 = pd.DataFrame(columns=['CNTR_CODE', 'Risk_damage', 'pot_tot_loss','annual_tot_loss'])
df2 = pd.DataFrame(columns=['CNTR_CODE', 'Risk_damage', 'pot_tot_loss','annual_tot_loss'])
df3 = pd.DataFrame(columns=['CNTR_CODE', 'Risk_damage', 'pot_tot_loss','annual_tot_loss'])
df4 = pd.DataFrame(columns=['CNTR_CODE', 'Risk_damage', 'pot_tot_loss','annual_tot_loss'])
df5 = pd.DataFrame(columns=['CNTR_CODE', 'Risk_damage', 'pot_tot_loss','annual_tot_loss'])
df6 = pd.DataFrame(columns=['CNTR_CODE', 'Risk_damage', 'pot_tot_loss','annual_tot_loss'])
df7 = pd.DataFrame(columns=['CNTR_CODE', 'Risk_damage', 'pot_tot_loss','annual_tot_loss'])
df8 = pd.DataFrame(columns=['CNTR_CODE', 'Risk_damage', 'pot_tot_loss','annual_tot_loss'])
df9 = pd.DataFrame(columns=['CNTR_CODE', 'Risk_damage', 'pot_tot_loss','annual_tot_loss'])

df1[["CNTR_CODE", 'Risk_damage', 'pot_tot_loss','annual_tot_loss']]=copy_df[["CNTR_CODE", 'Risk_damage0','pot_tot_loss00', 'annual_tot_loss00']]
df2[["CNTR_CODE", 'pot_tot_loss','annual_tot_loss']]=copy_df[["CNTR_CODE", 'pot_tot_loss01','annual_tot_loss01']]
df3[["CNTR_CODE", 'pot_tot_loss','annual_tot_loss']]=copy_df[["CNTR_CODE", 'pot_tot_loss02','annual_tot_loss02']]

df4[["CNTR_CODE", 'Risk_damage', 'pot_tot_loss','annual_tot_loss']]=copy_df[["CNTR_CODE", 'Risk_damage1','pot_tot_loss10', 'annual_tot_loss10']]
df5[["CNTR_CODE", 'pot_tot_loss','annual_tot_loss']]=copy_df[["CNTR_CODE", 'pot_tot_loss11','annual_tot_loss11']]
df6[["CNTR_CODE", 'pot_tot_loss','annual_tot_loss']]=copy_df[["CNTR_CODE", 'pot_tot_loss12','annual_tot_loss12']]

df7[["CNTR_CODE", 'Risk_damage', 'pot_tot_loss','annual_tot_loss']]=copy_df[["CNTR_CODE", 'Risk_damage2','pot_tot_loss20', 'annual_tot_loss20']]
df8[["CNTR_CODE", 'pot_tot_loss','annual_tot_loss']]=copy_df[["CNTR_CODE", 'pot_tot_loss21','annual_tot_loss21']]
df9[["CNTR_CODE", 'pot_tot_loss','annual_tot_loss']]=copy_df[["CNTR_CODE", 'pot_tot_loss22','annual_tot_loss22']]


new_df=pd.concat([df1, df2,df3,df4,df5,df6,df7,df8,df9]).reset_index() 

答案 1 :(得分:0)

首先采用这样的临时数据框

git status

这将给出两个数据帧,然后再连接两个

df1[["a", "b"]]=df[["a1", "b1"]]
df2[["a", "b"]]=df[["a2", "b2"]]