快速迭代大型数据框中的行以确定列的内容

iterate over rows in a large dataframe fast to determine contents for a column

对于以下数据框:

import numpy as np
import pandas as pd
df = pd.DataFrame({'chr_key':  [1, 1, 1, 2, 2, 3, 4],
                   'position': [123,124,125,126,127,128,129],
                   'hit_count': [20,19,18,17,16,15,14]})

df['strand'] = np.nan

我想修改 strand 列,以便:

for i in range(0, len(df['position'])):
    if df['chr_key'][i] == df['chr_key'][i+1] and df['hit_count'][i] >= df['hit_count'][i+1]:
        df['strand'][i] = 'F'

    else:
        df['strand'][i] = 'R'

我的实际 df 是 >100k 行,所以 for-loop 是可以想象的慢。有没有快速的方法来实现这个?

我修改了我的原始数据框。输出将是:

df = pd.DataFrame({'chr_key' : [1, 1, 1, 2, 2, 3, 4], 'position' : [123, 124, 125, 126, 127, 128, 129], 'hit_count' : [20, 19, 18, 17, 16, 15, 14], 'strand': ['R', 'R', 'F', 'R', 'F', 'F', 'F']})

因为只有3个chr_key == 1所以到了第三行,由于没有第i+1个比较行,所以strand的值会默认为F

我正在使用 np.whereshift

c1=(df.chr_key==df.chr_key.shift(-1))
c2=(df.hit_count>=df.hit_count.shift(-1))
df['strand']=np.where(c1&c2,'F','R')

你可以试试这个:

import pandas as pd

df = pd.DataFrame({'chr_key' : [1, 1, 1, 2, 2, 3, 4], 'position' : [123, 124, 125, 126, 127, 128, 129], 'hit_count' : [20, 19, 18, 17, 16, 15, 14]})

df['strand'] = 'R'

idx_1 = df.chr_key == df.chr_key.shift(-1) 
idx_2 = df.hit_count >= df.hit_count.shift(-1)

df.loc[idx_1 & idx_2, 'strand'] = 'F'

使用lociloc方法访问pandas数据框是更好的做法:https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html