【问题标题】:Assigning to multiple columns at once (python pandas)一次分配给多个列(python pandas)
【发布时间】:2018-05-06 03:09:31
【问题描述】:

所以我昨天开始了一个问题:Multiple assignment in pandas based on the values in the same row,我想知道如何对一行数据进行排名并将排名分配给同一行中的不同列。我已经从这里按照 Ed Chum 的建议弄清楚了如何做到这一点: how to apply a function to multiple columns in a pandas dataframe at one time.

它确实有效,但后来我注意到我在此过程中创建了不正确的列。一旦我修复了这个错误,它就不再起作用了......

所以我尝试在玩具示例上重新创建问题,但它也不适用于玩具示例。有人可以指出错误,这是代码(python 3):

import pandas as pd
import numpy as np  
import scipy


df = pd.DataFrame(data={'a':[1,2,3],'b':[2,1,3],'c':[3,1,2],
                        'rank_a':[np.nan]*3,'rank_b':[np.nan]*3,'rank_c':[np.nan]*3})

def apply_rank(row):
    vals = [row['a'],row['b'],row['c']]
    ranked = scipy.stats.rankdata(vals)
    d = len(vals)+1
    ranked = [rank/d for rank in ranked]
    rank_cols = [col for col in row.index if col.startswith("rank_")]
    print("ranked: "+str(ranked))

    for idx,rank_col in enumerate(rank_cols): 
        print("Before: "+str(row[rank_col]))
        row[rank_col] = ranked[idx]
        print("After: "+str(row[rank_col]))

然后运行: df.apply(lambda row: apply_rank(row),axis=1),查看作业是否正确完成。

然后运行: df 看到没有分配任何内容.. facepalm

【问题讨论】:

标签: python pandas


【解决方案1】:

您可以返回 Series 并为新列的值提供索引:

def apply_rank(row):
    vals = [row['a'],row['b'],row['c']]
    ranked = scipy.stats.rankdata(vals)
    d = len(vals)+1
    ranked = [rank/d for rank in ranked]
    rank_cols = [col for col in row.index if col.startswith("rank_")]

    return pd.Series(ranked, index=rank_cols)

df = df.apply(lambda row: apply_rank(row),axis=1)
print (df)
   rank_a  rank_b  rank_c
0   0.250   0.500   0.750
1   0.750   0.375   0.375
2   0.625   0.625   0.250

编辑:如果之前存在新列,可以将数据附加到它们并返回row

def apply_rank(row):
    vals = [row['a'],row['b'],row['c']]
    ranked = scipy.stats.rankdata(vals)
    d = len(vals)+1
    ranked = [rank/d for rank in ranked]
    rank_cols = [col for col in row.index if col.startswith("rank_")]

    row.loc[rank_cols] = ranked
    return row

df = df.apply(apply_rank,axis=1)
print (df)
     a    b    c  rank_a  rank_b  rank_c
0  1.0  2.0  3.0   0.250   0.500   0.750
1  2.0  1.0  1.0   0.750   0.375   0.375
2  3.0  3.0  2.0   0.625   0.625   0.250

【讨论】:

  • 是否也可以保留其中的原始列?
  • 完美!传奇!
  • 不客气!如果有什么工作,我已经有类似的快乐了;)
  • 我在这上面花了两个小时... :)
【解决方案2】:

df[col].iloc[[2,3,4] = 2

在dataframe df中,在特定的列名col处,对于索引(2,3,4)我们可以将值设置为2,如上所示

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-05
    • 2014-01-16
    • 2018-10-18
    • 2020-11-20
    • 2022-01-24
    相关资源
    最近更新 更多