简体   繁体   English

如果列数小于行数,则添加虚拟列

[英]Adding Dummy Column If Number of Column is less than number of rows

I have non-square table which look like this:我有一个看起来像这样的非方桌:

input:
        A   B   C
    0   4   2   5 
    1   2   6   8
    2   8   3   4
    3   4   2   5
    4   3   6   7
    5   7   3   8

the output should be like this output 应该是这样的

output:
        A   B   C   d1   d2   d3
    0   4   2   5   0    0    0
    1   2   6   8   0    0    0
    2   8   3   4   0    0    0
    3   4   2   5   0    0    0
    4   3   6   7   0    0    0
    5   7   3   8   0    0    0

Since the number of columns is 3 and the rows are 6, therefore I want to create dummy columns as much as the number of rows.由于列数为 3,行数为 6,因此我想创建与行数一样多的虚拟列。 So in this case, I need 3 columns more, with all 0 values on them.因此,在这种情况下,我还需要 3 列,其中所有值均为 0。 And I also want the column name is "d1", "d2", "d3", etc. Could anyone help me on this matter?而且我还希望列名是“d1”、“d2”、“d3”等。有人可以帮我解决这个问题吗? Thanks in advance!提前致谢!

You can do reindex你可以做reindex

out = df.reindex(columns = df.columns.to_list()+[*range(df.shape[0]-df.shape[1])],fill_value=0)
Out[65]: 
   A  B  C  0  1  2
0  4  2  5  0  0  0
1  2  6  8  0  0  0
2  8  3  4  0  0  0
3  4  2  5  0  0  0
4  3  6  7  0  0  0
5  7  3  8  0  0  0

暂无
暂无

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

相关问题 计算大于当前行值但小于其他列值的连续行数 - Count number of consecutive rows that are greater than current row value but less than the value from other column 使用pandas / python在数据框中出现列值小于某个数字时删除行? - Remove rows when the occurrence of a column value in the data frame is less than a certain number using pandas/python? 如何添加虚拟行以使 pandas 中特定列的每个列值的行数相等 - How to add dummy rows to make number of rows equal for each column value of a particular column in pandas 如何返回数据框/系列中小于特定数字的列元素? - How to return elements of a column in a dataframe/series that are less than a specific number? 统计每列中小于 x 的元素个数 - Count number of elements in each column less than x 使用python向列添加数字 - Adding a number to a column with python 如果数据框列中的数字小于10,如何在数字前添加零 - how to add zero before a number if the number is less than 10 in a dataframe column 仅当列中的 NaN 少于给定数量时,如何用列均值替换 NaN? - How to replace NaN with column mean only if less than a given number of NaN in a column? 向具有不同行数的pandas数据框中添加新列 - Adding a new column to a pandas dataframe with different number of rows 当连续列值小于某个数字时,pandas 逐行求和 - pandas row wise sum when when consecutive column value is less than a certain number
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM