使用熊猫适用

时间:2016-10-25 07:28:33

标签: python pandas dataframe

我有一个类似于以下示例的数据框:

sample = {'col1': [50.6, 30.67, 40.5, 0, 0, 0],
          'col2': [40.74, 30.33, 41.00, 0, 0, 0]}
df_sample = pd.DataFrame(sample)

现在,在col2col3中,条目代表两个不同的值。例如,对于条目50.6,代表val1 = 5val2 = 0.6。另一个例子是41.00。此值代表41.0

基本上,我想得到的是一个可以按如下方式计算的列:

df_sample['res'] = df_sample.apply(lambda x: 
    ((x['col2']//10)*(x['col2']%10) + (x['col3']//10)*(x['col3']%10)) 
            / (x['col2']//10 + x['col3']//10), axis=1)
df_sample.fillna(0)

基本上,它从每列获得的值中获得加权平均值。现在,我想要做的是扩展这个方法,让我们说二十列,而不是在DataFrame中对每个列名进行硬编码。请指教。

2 个答案:

答案 0 :(得分:2)

只需创建要用于计算的列的子集,您就可以对子集df本身执行操作,而不是在每个系列对象上调用函数:

np.random.seed(42)
df = pd.DataFrame(np.random.uniform(0, 100, (100, 25))).add_prefix('col')
df.shape
(100, 25)

# Take first 20 columns (for eg)
df_sample = df.iloc[:, :20] 
df['res'] = (df_sample // 10 * df_sample % 10).sum(1)/(df_sample // 10).sum(1)

答案 1 :(得分:0)

您可以省略apply,而是使用SeriesDataframes列):

sample = {'col2': [50.6, 30.67, 40.5, 0, 0, 0],
          'col3': [40.74, 30.33, 41.00, 0, 0, 0],
          'col4': [70.6, 80.67, 70.5, 0, 0, 0],
          'col5': [10.74, 50.33, 51.00, 0, 0, 0]}
df_sample = pd.DataFrame(sample)
print (df_sample)
    col2   col3   col4   col5
0  50.60  40.74  70.60  10.74
1  30.67  30.33  80.67  50.33
2  40.50  41.00  70.50  51.00
3   0.00   0.00   0.00   0.00
4   0.00   0.00   0.00   0.00
5   0.00   0.00   0.00   0.00

我认为你需要:

print ((((df_sample['col2']//10 * df_sample['col2']%10) + 
        (df_sample['col3']//10 * df_sample['col3']%10) +
        (df_sample['col4']//10 * df_sample['col4']%10) +
        (df_sample['col5']//10 * df_sample['col5']%10)) 
         / (df_sample['col2']//10 + df_sample['col3']//10 + 
            df_sample['col4']//10 + df_sample['col5']//10)).fillna(0))

0    0.641176
1    0.526842
2    0.725000
3    0.000000
4    0.000000
5    0.000000
dtype: float64

print (((df_sample//10 * df_sample%10).sum(axis=1).div((df_sample//10).sum(axis=1)))
         .fillna(0))
0    0.641176
1    0.526842
2    0.725000
3    0.000000
4    0.000000
5    0.000000
dtype: float64

<强>计时

In [114]: %timeit ((((df_sample['col2']//10 * df_sample['col2']%10) + (df_sample['col3']//10 * df_sample['col3']%10) + (df_sample['col4']//10 * df_sample['col4']%10) + (df_sample['col5']//10 * df_sample['col5']%10))  / (df_sample['col2']//10 + df_sample['col3']//10 + df_sample['col4']//10 + df_sample['col5']//10)).fillna(0))
100 loops, best of 3: 2.03 ms per loop

In [115]: %timeit (((df_sample//10 * df_sample%10).sum(axis=1).div((df_sample//10).sum(axis=1))).fillna(0))
1000 loops, best of 3: 897 µs per loop
相关问题