簡體   English   中英

如何在dataframe中的一系列數字中添加前導零,然后添加后綴?

[英]how to add leading zeros to a series of numbers in a dataframe, and then add a suffix?

我有一個關於操縱 dataframe 的問題。 就我而言,dataframe 有一列,其中有從 1 到 1999 的數字。

我想做以下操作:

  1. 在數字前添加零以使其成為 6 位代碼,例如 0000001,000002,...001999
  2. 為 6 位代碼添加后綴,例如 000001xx,000002xx,...001999xx

我能怎么做?

In [93]: df = pd.DataFrame({"num":range(1, 2000)})
In [94]: df
Out[94]:
       num
0        1
1        2
2        3
3        4
4        5
...    ...
1994  1995
1995  1996
1996  1997
1997  1998
1998  1999

[1999 rows x 1 columns]
In [97]: df["new_num"] = df["num"].map("{0:0=6d}".format)
In [98]: df["new_num"] = df["new_num"] + "xx"

In [99]: df
Out[99]:
       num   new_num
0        1  000001xx
1        2  000002xx
2        3  000003xx
3        4  000004xx
4        5  000005xx
...    ...       ...
1994  1995  001995xx
1995  1996  001996xx
1996  1997  001997xx
1997  1998  001998xx
1998  1999  001999xx

[1999 rows x 2 columns]

您可以將以上 2 個步驟合二為一

df["num"].map("{0:0=6d}xxx".format)

您可以通過應用 lambda (或 map參見 bigbounty 的答案)從您的號碼創建一個字符串來計算格式化的字符串列:

import pandas as pd


df = pd.DataFrame(({ "nums": range(100,201)}))

# format the string in one go
df["modded"] = df["nums"].apply(lambda x:f"{x:06n}xxx")
print(df)

Output:

     nums     modded
0     100  000100xxx
1     101  000101xxx
2     102  000102xxx
..    ...        ...
98    198  000198xxx
99    199  000199xxx
100   200  000200xxx

只需使用str.rjust

import pandas as pd

df = pd.DataFrame({"num": range(1, 2000)})

print(df.num.astype(str).str.rjust(6, '0') + "xx")

0       000001xx
1       000002xx
2       000003xx
3       000004xx
4       000005xx
          ...   
1994    001995xx
1995    001996xx
1996    001997xx
1997    001998xx
1998    001999xx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM