1

次のように、データフレームの2つの列から値を交換するのに苦労しています。

rs649071 rs640249 0.265 0.49 
rs647621 rs640249 0.227 0.34 
rs644339 rs640249 0.116 0.08 
rs641563 rs640249 1.0 33.96 
rs640249 rs11073074 0.248 0.77 
rs640249 rs11637397 0.194 0.68 

アイデアは、列2の各セルがrs640249であるかどうかをテストし、そうでない場合は、列1から対応する文字列に変更することです。その逆も同様です。このようにすると、最終的な結果は次のようになります。

rs649071 rs640249 0.265 0.49 
rs647621 rs640249 0.227 0.34 
rs644339 rs640249 0.116 0.08 
rs641563 rs640249 1.0 33.96 
rs11073074 rs640249 0.248 0.77 
rs11637397 rs640249 0.194 0.68 

タプルを反復処理しようとしましたが、タプルはアイテムの割り当てをサポートしていません。

rscode='rs640249'
for inf in LDfiles:
    df = read_csv(inf, sep='\t', skiprows=1, names=['A', 'B', 'C'])
    for tup in df.itertuples():
        if tup[2] != rscode:
            tup[1], tup[2] = tup[2], tup[1]
        print(tup)
4

3 に答える 3

1

これを行う1つの方法は、 applyを使用することです。

def my_fun(row):
    if row['col1'] == 'rs640249':
        return row['col2'], row['col1']
    else:
        return row['col1'], row['col2']

df = df.apply(my_fun, axis=1)

1つの列の値のみを変更する場合でも、次を使用できますapply

def my_fun2(row, colID):
    if row[colID][0] == 'rs640249':
        return row[colID][::-1] #reverse the tuple
    else:
        return row[colID]

df[colID] = df.apply(lambda x: my_fun2(x, colID), axis=1)

注:my_fun2は単一の値を返すため、今回applyはシリーズを返すため、適用方法を少し変更する必要があります。

例:

df
#                             0
# 0    ('rs649071', 'rs640249')
# 1  ('rs640249', 'rs11073074')

df[0] = df.apply(lambda x: my_fun2(x,0), axis=1)
#                             0
# 0    ('rs649071', 'rs640249')
# 1  ('rs11073074', 'rs640249')
于 2012-09-28T22:50:31.837 に答える
1

将来の参照のために、ここに可能な解決策があります:

    for row_index, row in df.iterrows():
        if row['L1'] == 'rs640249':
            df.set_value(row_index, 'L1' , row['L2'])
            df.set_value(row_index, 'L2' , row['L1'])

一番、

于 2012-10-01T20:43:43.057 に答える
0

配列操作を使用して、次のようなことを試してみませんか。

condition = df['L1'] == 'rs640249'
tmp = df['L1'].copy()
df['L1'][condition] = df['L2'][condition]
df['L2'][condition] = tmp[condition]
于 2012-10-20T19:42:29.593 に答える