Python是進行數據分析的一種出色語言,主要是因為以數據為中心的python軟件包具有奇妙的生態係統。 Pandas是其中的一種,使導入和分析數據更加容易。
Pandas dataframe.reindex()
函數使用可選的填充邏輯使DataFrame符合新索引,將NA /NaN放置在先前索引中沒有值的位置。除非新索引等於當前索引並且copy = False,否則將生成一個新對象。
用法: DataFrame.reindex(labels=None, index=None, columns=None, axis=None, method=None, copy=True, level=None, fill_value=nan, limit=None, tolerance=None)
參數:
labels:新標簽/索引使“ axis”指定的軸與之一致。
index, columns:要符合的新標簽/索引。最好是一個Index對象,以避免重複數據
axis:軸到目標。可以是軸名稱(“索引”,“列”)或數字(0、1)。
method:{None,“ backfill” /“ bfill”,“ pad” /“ ffill”,“ nearest”},可選
copy:即使傳遞的索引相同,也返回一個新對象
level:在一個級別上廣播,在傳遞的MultiIndex級別上匹配索引值
fill_value:在計算之前,請使用此值填充現有的缺失(NaN)值以及成功完成DataFrame對齊所需的任何新元素。如果兩個對應的DataFrame位置中的數據均丟失,則結果將丟失。
limit:向前或向後填充的最大連續元素數
tolerance:不完全匹配的原始標簽和新標簽之間的最大距離。匹配位置處的索引值最滿足方程abs(index [indexer]-target)
返回:重新索引:DataFrame
範例1:采用reindex()
用於重新索引 DataFrame 的函數。默認情況下,新索引中在 DataFrame 中沒有對應記錄的值被分配為NaN。
注意:我們可以通過將值傳遞給關鍵字fill_value來填充缺失的值。
# importing pandas as pd
import pandas as pd
# Creating the dataframe
df = pd.DataFrame({"A":[1, 5, 3, 4, 2],
"B":[3, 2, 4, 3, 4],
"C":[2, 2, 7, 3, 4],
"D":[4, 3, 6, 12, 7]},
index =["first", "second", "third", "fourth", "fifth"])
# Print the dataframe
df
讓我們使用dataframe.reindex()
重新索引 DataFrame 的函數
# reindexing with new index values
df.reindex(["first", "dues", "trois", "fourth", "fifth"])
輸出:
注意輸出,新索引填充為NaN
值,我們可以使用參數fill_value填寫缺少的值
# filling the missing values by 100
df.reindex(["first", "dues", "trois", "fourth", "fifth"], fill_value = 100)
輸出:
範例2:采用reindex()
重新索引列軸的函數
# importing pandas as pd
import pandas as pd
# Creating the first dataframe
df1 = pd.DataFrame({"A":[1, 5, 3, 4, 2],
"B":[3, 2, 4, 3, 4],
"C":[2, 2, 7, 3, 4],
"D":[4, 3, 6, 12, 7]})
# reindexing the column axis with
# old and new index values
df.reindex(columns =["A", "B", "D", "E"])
輸出:
注意,我們有NaN
重新編製索引後,新列中的值會發生變化,我們可以解決重新編製索引時遺漏的值。通過論證fill_value
函數。
# reindex the columns
# fill the missing values by 25
df.reindex(columns =["A", "B", "D", "E"], fill_value = 25)
輸出:
相關用法
- Python pandas.map()用法及代碼示例
- Python Pandas Series.str.len()用法及代碼示例
- Python Pandas.factorize()用法及代碼示例
- Python Pandas TimedeltaIndex.name用法及代碼示例
- Python Pandas dataframe.ne()用法及代碼示例
- Python Pandas Series.between()用法及代碼示例
- Python Pandas DataFrame.where()用法及代碼示例
- Python Pandas Series.add()用法及代碼示例
- Python Pandas.pivot_table()用法及代碼示例
- Python Pandas Series.mod()用法及代碼示例
- Python Pandas Dataframe.at[ ]用法及代碼示例
- Python Pandas Dataframe.iat[ ]用法及代碼示例
- Python Pandas.pivot()用法及代碼示例
- Python Pandas dataframe.mul()用法及代碼示例
- Python Pandas.melt()用法及代碼示例
注:本文由純淨天空篩選整理自Shubham__Ranjan大神的英文原創作品 Python | Pandas dataframe.reindex()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。