简体   繁体   中英

Python : Add a column into a dataframe with different length repeating the added column till fill the dataframe length

Hos I could a do this one:

Df1:

A B
01 AA
02 AB
03 AC
05 AD

Df2:

C
11
12

Dataframe looking for:

A B C
01 AA 11
02 AB 12
03 AC 11
05 AD 12

How could I reach this solution?

You can use np.tile to repeat the elements of column C :

m, n = len(df1), len(df2)
df1['C'] = np.tile(df2['C'], int(np.ceil(m / n)))[:m]

Result:

   A   B   C
0  1  AA  11
1  2  AB  12
2  3  AC  11
3  5  AD  12

You can do concat :

   >>> pd.concat([df1,df2.append(df2).reset_index(drop=True)],axis=1)

       A   B     C
    0  1  AA  11.0
    1  2  AB  12.0
    2  3  AC  11.0
    3  5  AD  12.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM