2 回答

TA貢獻2080條經(jīng)驗 獲得超4個贊
DataFrame運行應用功能后,您可以調整列的順序。例如:
df = df.apply(func, axis = 1)
df = df[['my_customers', 'email', 'other_column', 'new_column']]
為了減少重復的數(shù)量(即必須重新輸入所有列名),您可以在調用 apply 函數(shù)之前獲取現(xiàn)有的列集:
columns = list(df.columns)
df = df.apply(func, axis = 1)
df = df[columns + ['new_column']]
根據(jù)作者對原始問題的編輯進行更新。雖然我不確定選擇的數(shù)據(jù)結構(將 API 結果存儲在數(shù)據(jù)框中)是否是最佳選擇,但一種簡單的解決方案可能是在調用應用函數(shù)后提取新列。
# Store the existing columns before calling apply
existing_columns = list(df.columns)
df = df.apply(func, axis = 1)
all_columns = list(df.columns)
new_columns = [column for column in all_columns if column not in existing_columns]
df = df[columns + new_columns]
對于性能優(yōu)化,您可以將現(xiàn)有列存儲在 aset而不是 alist中,由于 Python 中集合數(shù)據(jù)結構的散列性質,這將在恒定時間內產(chǎn)生查找。這將更existing_columns = list(df.columns)改為existing_columns = set(df.columns).
最后,正如@Parfait 在他們的評論中非常友好地指出的那樣,上面的代碼可能會引發(fā)一些折舊警告。使用pandas.DataFrame.reindex而不是df = df[columns + new_columns]將使警告消失:
new_columns_order = [columns + new_columns]
df = df.reindex(columns=new_columns_order)

TA貢獻1898條經(jīng)驗 獲得超8個贊
發(fā)生這種情況是因為您沒有為新列分配值 if row["other_column"] != 'yes'。試試這個:
def func(row):
if row['other_column'] == 'yes':
row['new_column'] = 'Hello'
return row
else:
row['new_column'] = ''
return row
df.apply(func, axis = 1)
您可以選擇row["new_column"] == 'no'任何值。我只是把它留空。
添加回答
舉報