簡體   English   中英

使用pandas操作將列添加到pandas數據框

[英]Add a column to a pandas data frame using a pandas operation

如果我有一個數據幀,並且需要在給定的列上執行一些操作並產生一個新的列,那么有沒有比下面的函數更好的方法?

我不想更改原始列。 我想繼續為此和任何類似的操作添加新列。

但是在下面的代碼中,似乎有太多行。 也就是說,pandas中的rank()函數非常方便。 在我看來,應該在某個位置對數據框說一些參數,“嘿,應用您已經知道的此功能,但是不要像您那樣對原始列本身進行處理,而是在最后添加一個新列數據幀”

有這種方法嗎? 還是有什么辦法可以使下面的代碼更簡潔/優美,並達到相同的結果? 我剛才的內容似乎很冗長。 我也為其他事情執行此操作,例如,我具有相同類型的cut()函數。 我將在其他一些操作中這樣做。 似乎很常見,應該會更容易。

謝謝!

def rank(pdfAll, nOldColIndex, sNewColName, sMethod, bAsc):
"""Appends a ranked column to a DataFrame based on an existing column.  

   nOldColIndex is the index of the column with the original data.
   sNewColName is the name of the new column.  
   sMethod goes to the pandas rank function to influence ranking behavior.
   bAsc goes to the pandas rank function to influence ranking behavior.
   pdfAll[nOldColIndex] must have numeric contents.

"""

serOldCol = pdfAll.ix[:,nOldColIndex]
serOldCol.name = sNewColName

serNewCol = serOldCol.rank(method=sMethod, ascending=bAsc)
pdfNewCol = pd.DataFrame(serNewCol)

pdfAll = pd.merge(pdfAll, pdfNewCol, left_index=True, right_index=True)

return pdfAll 

我不確定這種概括是什么,但是您是否有機會嘗試做一些

df['newColumn'] = df.oldColumn.rank()

概括該功能,如果您想連續執行某項操作,則可以執行

df.apply(lambda x: x.oldColumn * x.otherOldColumn, axis=1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM