python - 在 Pandas 数据框中的两列之间传输值

标签 python pandas python-2.7

我有一个像这样的 Pandas 数据框:

p q
0.5 0.5
0.6 0.4
0.3 0.7
0.4 0.6
0.9 0.1

所以,我想知道,如何将更大的值传输到 p 列,反之亦然(将更小的值传输到 q 列),如下所示:

p q
0.5 0.5
0.6 0.4
0.7 0.3
0.6 0.4
0.9 0.1

最佳答案

您可以使用 np.where() 存储一些条件序列,然后将它们应用于数据框:

s1 = np.where(df['p'] < df['q'], df['q'], df['p'])
s2 = np.where(df['p'] > df['q'], df['q'], df['p'])
df['p'] = s1
df['q'] = s2
df
Out[1]: 
     p    q
0  0.5  0.5
1  0.6  0.4
2  0.7  0.3
3  0.6  0.4
4  0.9  0.1

你也可以使用 .where():

s1 = df['p'].where(df['p'] > df['q'], df['q'])
s2 = df['p'].where(df['p'] < df['q'], df['q'])
df['p'] = s1
df['q'] = s2
df

我测试了从 100 行到 100 万行的不同行的执行时间,需要传递 axis=1 的答案可能会慢 10,000 倍!:

  1. Erfan 的 numpy 答案看起来是处理大型数据集最快的毫秒级答案
  2. 我的 .where() 答案也有很好的性能,可以将执行时间保持在毫秒级(我假设 `np.where() 会产生类似的结果。
  3. 我以为 MHDG7 的回答会是最慢的,但实际上它比 Alexander 的回答更快。
  4. 我猜亚历山大的回答很慢,因为它需要传递 axis=1。事实上,MGDG7 和 Alexander 的答案是按行的(使用 axis=1),这意味着它可以极大地降低大型数据帧的速度。

如您所见,一百万行数据帧需要几分钟才能执行。而且,如果您有 1000 万行到 1 亿行的数据框,这些单行代码可能需要数小时才能执行。


from timeit import timeit
df = d.copy()

def df_where(df):
    s1 = df['p'].where(df['p'] > df['q'], df['q'])
    s2 = df['p'].where(df['p'] < df['q'], df['q'])
    df['p'] = s1
    df['q'] = s2
    return df


def agg_maxmin(df):
    df[['p', 'q']] = df[['p', 'q']].agg([max, min], axis=1)
    return df


def np_flip(df):
    df = pd.DataFrame(np.flip(np.sort(df), axis=1), columns=df.columns)
    return df


def lambda_x(df):
    df = df.apply(lambda x: [x['p'],x['q']] if x['p']>x['q'] else [x['q'],x['p']],axis=1,result_type='expand')
    return df


res = pd.DataFrame(
    index=[20, 200, 2000, 20000, 200000],
    columns='df_where agg_maxmin np_flip lambda_x'.split(),
    dtype=float
)

for i in res.index:
    d = pd.concat([df]*i)
    for j in res.columns:
        stmt = '{}(d)'.format(j)
        setp = 'from __main__ import d, {}'.format(j)
        print(stmt, d.shape)
        res.at[i, j] = timeit(stmt, setp, number=1)

res.plot(loglog=True);

enter image description here

关于python - 在 Pandas 数据框中的两列之间传输值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64298403/

相关文章:

python - 检查没有符号的大整数值的类型

python - Pyramid :ACL 中的 ACE 顺序

python - 将 HDF 5 文件读入 Pandas 时,如何避免字符串被读取为字节?

python Pandas : read file skipping commented

python - 计算重复行并填充列

python - 动态从列表-字典混合列表中获取值

Python MySQL 和上下文管理器 : __exit__ Attribute error

python - 在 Python C API 中使用多个模块/类型?

python - 无法为 Dask 安装 tlz 模块 Python

python os.path.expanduser() 这总是正确的吗