使用 applymap 函式編寫一個 Python 程式來列印資料框中所有列的元素長度


資料框中所有列的元素長度的結果如下:

Dataframe is:
   Fruits    City
0 Apple    Shimla
1 Orange   Sydney
2 Mango    Lucknow
3 Kiwi    Wellington
Length of the elements in all columns
   Fruits City
0    5    6
1    6    6
2    5    7
3    4    10

解決方案

要解決這個問題,我們將按照以下步驟操作:

  • 定義一個數據框

  • 在 lambda 函式內使用 df.applymap 函式計算所有列中元素的長度,如下所示:

df.applymap(lambda x:len(str(x)))

示例

讓我們檢查以下程式碼以獲得更好的理解:

import pandas as pd
df = pd.DataFrame({'Fruits': ["Apple","Orange","Mango","Kiwi"],
                     'City' : ["Shimla","Sydney","Lucknow","Wellington"]
                  })
print("Dataframe is:\n",df)
print("Length of the elements in all columns")
print(df.applymap(lambda x:len(str(x))))

輸出

Dataframe is:
  Fruits    City
0 Apple    Shimla
1 Orange   Sydney
2 Mango    Lucknow
3 Kiwi    Wellington
Length of the elements in all columns:
   Fruits City
0    5    6
1    6    6
2    5    7
3    4    10

更新於:2021年2月25日

309 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告