如何制作等长的DataFrame列?
How to make DataFrame column of equal length?
我有一个如下所示的 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
必要时可以使用str.zfill
, but first convert int
values to str
by astype
:
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
我有一个如下所示的 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
必要时可以使用str.zfill
, but first convert int
values to str
by astype
:
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