简体   繁体   English

为熊猫 dataframe 添加一列

[英]Adding a column to panda dataframe

I have been trying for hours to find a method to replicate columns n number of times and add them a Dataframe but has had little luck.我已经尝试了几个小时来找到一种方法来复制列 n 次并将它们添加到Dataframe但运气不佳。 Please help!请帮忙!

Current Dataframe:当前 Dataframe:

    0
0   2
1   4
2   5
3   6
4   9

Output: Output:

    0  1 2 ... 99
0   2  2 2     2
1   4  4 4     4 
2   5  5 5     5
3   6  6 6     6
4   9  9 9     9

As mention in comment by @sammywemmy you can use:-正如@sammywemmy 在评论中提到的,您可以使用:-

df=pd.concat([df]*100, axis = 'columns')

After that rename columns:-之后重命名列: -

df.columns=range(0,len(df.columns))
>>> df
   0
0  2
1  4
2  5
3  6
4  9

.iloc is another option .iloc是另一种选择

>>> df.iloc[:, [0] * 10]
   0  0  0  0  0  0  0  0  0  0
0  2  2  2  2  2  2  2  2  2  2
1  4  4  4  4  4  4  4  4  4  4
2  5  5  5  5  5  5  5  5  5  5
3  6  6  6  6  6  6  6  6  6  6
4  9  9  9  9  9  9  9  9  9  9

There could be several ways, one way is something like this:可能有几种方法,一种方法是这样的:

df= pd.DataFrame()
    for i in range(5):
        for j in range(0,10):
            df.loc[i,j] = i+j
        
df
     0    1    2    3    4    5     6     7     8     9
0  0.0  1.0  2.0  3.0  4.0  5.0   6.0   7.0   8.0   9.0
1  1.0  2.0  3.0  4.0  5.0  6.0   7.0   8.0   9.0  10.0
2  2.0  3.0  4.0  5.0  6.0  7.0   8.0   9.0  10.0  11.0
3  3.0  4.0  5.0  6.0  7.0  8.0   9.0  10.0  11.0  12.0
4  4.0  5.0  6.0  7.0  8.0  9.0  10.0  11.0  12.0  13.0

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

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