繁体   English   中英

在循环中在 Pandas DF 的特定列中附加行

[英]Appending rows in a specific column of a Pandas DF in a loop

我对 Pandas 很陌生,我有一个如下用例:我有一个 Dataframe,如:

print (df)

         date    sector symbol   val1  val2
0  2000-01-31        IT      A  82.10  19.2
1  2000-01-31        IT     AA  28.00  20.3
2  2000-01-31    Sports     AB  32.22   1.2
3  2000-02-27  Industry      c  16.60   3.5
4  2000-02-27  Industry     cc  96.24   2.6

“日期”、“部门”和“符号”是我的关键列。 我想对“日期”进行分组并按降序对“val1”和“val2”列进行排名,并创建一个新的数据框,其中包含键列和排名(val1 和 val2)而不是实际值。

我正在使用 for 循环遍历“日期”列表,并使用 pd.rank() 函数来查找排名。 这里的问题是,我无法正确地将行附加到 new_df(具有等级的那个)。 下面是我的代码:

    new_df = df.iloc[:,0:3] # This holds only key cols(date,sector,symbol)
    periods = np.sort(df['date'].dropna().unique())
    grped=df.groupby('date')
    for col in ['val1', 'val2']:
        new_df['{}_rnk'.format(col)] = "" #Creating a blank column for rank

        for dt in periods:
            t = pd.DataFrame()
            one = grped.get_group(dt)
            t = one[col].rank(ascending=flag,method='average')
            new_df['{}_rnk'.format(col)] = new_df['{}_rnk'.format(col)].append(t)

这没有给我正确的输出。 有人可以建议我做错了什么或可以说出更好的方法吗?

我相信这里可以使用GroupBy.rankadd_suffix并通过join附加到原始数据DataFrame

#set like need
flag=True
df1 = df.groupby('date')['val1', 'val2'].rank(ascending=flag,method='average')
df = df.join(df1.add_suffix('_rnk'))

print (df)
         date    sector symbol   val1  val2  val1_rnk  val2_rnk
0  2000-01-31        IT      A  82.10  19.2       3.0       2.0
1  2000-01-31        IT     AA  28.00  20.3       1.0       3.0
2  2000-01-31    Sports     AB  32.22   1.2       2.0       1.0
3  2000-02-27  Industry      c  16.60   3.5       1.0       2.0
4  2000-02-27  Industry     cc  96.24   2.6       2.0       1.0

另一种具有自定义函数的解决方案,其中包含用于降序和升序的指定列:

mapp = pd.DataFrame({'column_name':['val1','val2'], 'direction':['Asc','Desc']})
print(mapp)
  column_name direction
0        val1       Asc
1        val2      Desc

asc_cols = [k for k, v in mapp.set_index('column_name')['direction'].items() if v == 'Asc']
desc_cols = [k for k, v in mapp.set_index('column_name')['direction'].items() if v == 'Desc']
print(asc_cols)
['val1']
print (desc_cols)
['val2']

或者:

asc_cols = []
desc_cols = []

for k, v in mapp.set_index('column_name')['direction'].items():
    if v == 'Desc':
        asc_cols.append(k)
    elif v == 'Asc':
        desc_cols.append(k)  

print(asc_cols)
print (desc_cols)

def func(x):
    x[asc_cols] = x[asc_cols].rank(ascending=True,method='average').add_suffix('_rnk')
    x[desc_cols] = x[desc_cols].rank(ascending=False,method='average').add_suffix('_rnk')
    return x

df1 = df.groupby('date')['val1', 'val2'].apply(func)
print (df1)
   val1  val2
0   3.0   2.0
1   1.0   1.0
2   2.0   3.0
3   1.0   1.0
4   2.0   2.0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM