如何使DataFrame列长度相等?

时间:2017-03-06 08:45:13

标签: python python-3.x pandas dataframe padding

我有一个如下所示的DataFrame:

            data     top  number
497     Grossmont      5       1
498       College      5       2
500     Education     99       3
503          2004     99       3
504       Granite     227      3

目标是填充顶部列并与数字列连接,使顶部列的长度应该相同。

输出应如下所示:

            data     top  number
497    Grossmont    10005       1
498      College    20005       2
500    Education    30099       3
503         2004    30099       3
504      Granite    30227       3

1 个答案:

答案 0 :(得分:3)

您可以使用str.zfill,但如果需要,请先astypeint值转换为str

df.top = df.number.astype(str) + df.top.astype(str).str.zfill(4)
print (df)
          data    top  number
497  Grossmont  10005       1
498    College  20005       2
500  Education  30099       3
503       2004  30099       3
504    Granite  30227       3

如有必要,请转到int

df.top = (df.number.astype(str) + df.top.astype(str).str.zfill(4)).astype(int)
print (df)
          data    top  number
497  Grossmont  10005       1
498    College  20005       2
500  Education  30099       3
503       2004  30099       3
504    Granite  30227       3
相关问题