使用pandas框架添加pandas列的操作

2024-10-16 17:15:54 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有一个数据帧,我需要对一个给定的列执行一些操作并生成一个新的列,有没有比下面的函数更好的方法?在

我不想更改原始列。我想继续为这个和任何类似的操作添加新列。在

但在下面的代码中,似乎有太多的行。也就是说,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 

Tags: theto数据方法函数pandasindexcolumn
1条回答
网友
1楼 · 发布于 2024-10-16 17:15:54

我不知道这个概括是关于什么的,但是你有没有可能尝试做一些

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

泛化函数,如果你想在行的基础上做一些事情,你可以这样做

^{pr2}$

相关问题 更多 >