pandas 根据这些列的数量添加列

dsf9zpds  于 2023-08-01  发布在  其他
关注(0)|答案(1)|浏览(102)

我有这个df

  1. a b c d e 11 10 9 8 7 6 5 4 3 2 1
  2. 1241 535 2354 235 Acc_1 423 2342 2342 2342 234 234 7564 5345 76 4 976

字符串
背景:
1 to 11是帐户历史,1是最近的月份,11是最远的月份。a,b,c,d,e是我从数据中得到的变量。
我想要的是:
我正在寻找的是标准化的大小df。我的意思是,它总是从1到25,无论帐户历史是否上升到11,如df示例所示,空值填充为0值。
我想要这个df

  1. a b c d e 25 24 23 ... 8 7 6 5 4 3 2 1
  2. 1241 535 2354 235 Acc_1 0 0 0 ... 234 234 7564 5345 76 4 976 24


我尝试的是:

  1. while df.shape[1] != 30:
  2. df.insert(loc=5,
  3. column= (I dont know what to put here, but it must iterate from the missing number until it reaches 25 ),
  4. value=0)

**另一个问题:**在使用此df时,我无法通过名称df.1df['1']调用数值列,例如,出现的错误是:Error: 1。我所做的是使用iloc。为什么我不能按名称调用数值列?

yjghlzjz

yjghlzjz1#

您可以计算当前数据框中的最后一列,然后计算要添加的列数,创建具有所需形状的零数据框,并将初始和新的数据框水平堆叠。

  1. last_col = max(map(int, filter(lambda c: isinstance(c, int), df.columns)))
  2. new_df = pd.DataFrame(
  3. np.zeros((df.shape[0], 25 - last_col)),
  4. columns=range(last_col + 1, 26)
  5. )
  6. df = pd.concat([df, new_df], axis=1)
  7. df[list(df.columns[:5]) + list(range(1, 26))[::-1]]

字符串
输出量:

  1. a b c d e 25 24 23 22 21 ... 10 9 \
  2. 0 1241 535 2354 235 Acc_1 0.0 0.0 0.0 0.0 0.0 ... 2342 2342
  3. 8 7 6 5 4 3 2 1
  4. 0 2342 234 234 7564 5345 76 4 976
  5. [1 rows x 30 columns]


我不确定你的列名是数字还是字符串,我假设是字符串。如果不是,代码应该稍微调整一下。
注解表明这些列实际上是数字。更新了答案以处理它们。

展开查看全部

相关问题