所以我撰寫了一個簡短的函式,它基本上根據索引將一行從一個資料幀移動到另一個資料幀,同時保留索引。
如果我有這個測驗資料框和一個空的:
df = pd.DataFrame({'lower': ['a','b','c'],
'upper': ['A', 'B', 'C'],
'number': [1, 2, 3]},
index=['first', 'second', 'third'])
print(df, '\n\n')
empty = pd.DataFrame(columns=['lower', 'upper', 'number'])
print(empty, '\n\n')
我只是使用說明:
line = 'second'
empty = empty.append(df.loc[line])
df = df.drop(index=line)
有用。
但是如果我嘗試撰寫一個不純的函式來做同樣的事情,它只會修改函式內部的資料幀,而在函式外部它們保持不變!?
這是我的全部代碼:
def move_line(ind, source, destination):
row = source.loc[ind]
destination = destination.append(row)
source = source.drop(index=ind)
print('source inside function\n', source, '\n\n')
print('destination inside function\n', destination, '\n\n')
def main():
df = pd.DataFrame({'lower': ['a','b','c'],
'upper': ['A', 'B', 'C'],
'number': [1, 2, 3]},
index=['first', 'second', 'third'])
#print(df, '\n\n')
empty = pd.DataFrame(columns=['lower', 'upper', 'number'])
#print(empty, '\n\n')
move_line('second', df, empty)
print('source outside function\n', df, '\n\n')
print('destination outside function\n', empty)
uj5u.com熱心網友回復:
它只修改函式內部的資料幀,而在函式外部它們保持不變!?
那是因為DataFrame.append它不會改變原始 DataFrame,而是使用新行創建一個新 DataFrame。原始物件保持不變。DataFrame.drop默認情況下也不會更改原始物件,除非您通過inplace=True.
destination = destination.append(row) source = source.drop(index=ind)
在這里,您只是將名稱destination和重新系結source到由appendand回傳的物件drop,它們與destination和source最初指向的原始物件不同。原始物件保持不變。
要改變原始物件,您可以執行以下操作
def move_line(ind, source, destination):
row = source.loc[ind]
destination.loc[ind] = row
source.drop(index=ind, inplace=True)
print('source inside function\n', source, '\n\n')
print('destination inside function\n', destination, '\n\n')
df = pd.DataFrame({'lower': ['a','b','c'],
'upper': ['A', 'B', 'C'],
'number': [1, 2, 3]},
index=['first', 'second', 'third'])
#print(df, '\n\n')
empty = pd.DataFrame(columns=['lower', 'upper', 'number'])
#print(empty, '\n\n')
move_line('second', df, empty)
print('source outside function\n', df, '\n\n')
print('destination outside function\n', empty)
輸出:
source inside function
lower upper number
first a A 1
third c C 3
destination inside function
lower upper number
second b B 2
source outside function
lower upper number
first a A 1
third c C 3
destination outside function
lower upper number
second b B 2
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/357470.html
下一篇:將資料框列轉換為二進制
