简体   繁体   English

Python:将一列添加到 dataframe 中,具有不同的长度重复添加的列直到填充 dataframe 长度

[英]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: DF1:

A一个 B
01 01 AA AA
02 02 AB AB
03 03 AC交流电
05 05 AD广告

Df2: DF2:

C C
11 11
12 12

Dataframe looking for: Dataframe 寻找:

A一个 B C C
01 01 AA AA 11 11
02 02 AB AB 12 12
03 03 AC交流电 11 11
05 05 AD广告 12 12

How could I reach this solution?我怎样才能达到这个解决方案?

You can use np.tile to repeat the elements of column C :您可以使用np.tile重复列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 :你可以做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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 python 中向 dataframe 中添加不同列长度的页脚(行)? - How to add a footer(row) to the dataframe with different column length in python? 将列向量添加到不同长度的 dataframe - Add column vector to a dataframe of different length Python-将numpy数组作为列添加到具有不同长度的pandas数据帧 - Python - add a numpy array as column to a pandas dataframe with different length 在 PySpark 数据框中添加不同长度的列作为新列 - Add column with different length as new column in PySpark dataframe 匹配 2 个不同的 dataframe 但长度不同的列值 - Match column values of 2 different dataframe but of different length Pandas:将系列添加到数据框作为列(相同的索引,不同的长度) - Pandas: Add series to dataframe as a column (same index, different length) 使用不同长度的给定列表使 dataframe 具有不同的列长度 - Make dataframe having different column length with the given lists of different length 如何打开具有不同长度元组的 dataframe 列? - How to unpack a dataframe column with tuples of different length? 将具有不同长度的列表添加为数据帧的新列 - Adding list with different length as a new column to a dataframe 合并具有不同长度的多个数据框中的特定列 - Merge specific column in multiple dataframe with different length
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM