我試圖理解將資料檔案讀取到資料幀的代碼的最后 4 行pandas。我在這 4 行上方寫了一條評論;但我還是有點困惑。似乎代碼正在嘗試對空值等進行一些清理。問題:有人可以解釋一下代碼到底在做什么。似乎可以再簡化一點。
import pandas as pd
import numpy as np
pf = pd.read_csv('MyDataFile.txt', low_memory=False, sep=',', encoding='ISO-8859-1')
#trim the column names. Trimmed column will be the new column name
pf = pf.rename(columns=lambda x: x.strip())
#select all the columns that have undefined datatypes
pf_names = pf.select_dtypes(['object'])
#Select all columns with undefined datatypes and trim them
pf[pf_names.columns] = pf_names.apply(lambda x: x.str.strip())
#Replace the null values of dataframe columns with none
pf.replace([np.nan], [None], inplace=True)
uj5u.com熱心網友回復:
這將洗掉所有列名稱中的空格。所以'Column 1'將是'Column1'等等。
pf = pf.rename(columns=lambda x: x.strip())
這將選擇所有作為 dtype 物件的列。
pf_names = pf.select_dtypes(inculde='object')
如果您知道 Column1 和 Column2 是 dtype 物件,它將與以下內容相同:
pf_names = pf[pf[['Column1', 'Column2']]
這將與第一個條帶(洗掉空格)相同,但對于 dtype 物件的列的值。
pf[pf_names.columns] = pf_names.apply(lambda x: x.str.strip())
這將從資料框中洗掉所有 NaN 并替換為 None。
pf.replace(np.nan, None, inplace=True)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/435567.html
下一篇:在兩個資料集中用ID替換名稱
