スポンサーリンク

pandasのDataFrameで特定の列の文字列を置換

まずは、csvファイルを読み込みます。
col1,col2,col3の列名をつけています。

import pandas as pd

data = pd.read_csv('in.txt', names=('col1', 'col2', 'col3'))

DataFrame全体の文字列を置換する場合には、下記のように書きます。
下記は、'before'を'after'に置換しています。
完全一致であることに注意が必要です。

参考:[Python]pandasのDataFrameで部分一致で文字列を置換

dataReplace = data.replace('before', 'after')

DataFrameの特定の文字列を置換する場合には、下記のように書きます。
下記は、col1の列の'before'を'after'に置換しています。
同様に、完全一致であることに注意が必要です。
data.col1 = data.col1.replace('before', 'after')

スポンサーリンク

サンプルコード

例えば、下記のin.txtがあったとします。

 $ cat in.txt 
before,1,1
2,before,2
3,3,before

下記がサンプルコードになります。
 $ cat sample.py 
#!/usr/bin/env python3
# coding: UTF-8

import pandas as pd

data = pd.read_csv('in.txt', names=('col1', 'col2', 'col3'))
print(data)

dataReplace = data.replace('before', 'after')
print(dataReplace)

data.col1 = data.col1.replace('before', 'after')
print(data)

下記が実行結果になります。
 $ ./sample.py 
     col1    col2    col3
0  before       1       1
1       2  before       2
2       3       3  before
    col1   col2   col3
0  after      1      1
1      2  after      2
2      3      3  after
    col1    col2    col3
0  after       1       1
1      2  before       2
2      3       3  before

スポンサーリンク