[英]Pandas Removing Leading Zeros
我有一個 pivot 數據的簡短腳本。 第一列是一個 9 位的 ID 號,通常以零開頭,例如000123456
這是腳本:
df = pd.read_csv('source')
new_df = df.pivot_table(index = 'id', columns = df.groupby('id').cumcount().add(1), values = ['prog_id', 'prog_type'], aggfunc='first').sort_index(axis=1,level=1)
new_df.columns = [f'{x}_{y}' for x,y in new_df.columns]
new_df.to_csv('destination')
print(new_df)
盡管正在讀取 CSV 的 id 為000123456
,但 output 僅包含123456
即使設置顯式 dtype,Pandas 也會刪除前導零。 有沒有辦法告訴 Pandas 留下前導零?
根據對原始帖子的評論,將 dtype 設置為字符串:
df = pd.read_csv('source', dtype={'id':np.str})
您可以在閱讀 csv 文件"source"
后立即使用 pandas 的zfill()
方法。 基本上,您可以使用任意數量的零填充屬性"id"
的值,在這種特殊情況下,使數字長 9 位(3 個零 + 6 個原始數字)。 所以,我們會有:
df = pd.read_csv('source')
df.index = df.index.str.zfill(9)
# (...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.