【问题标题】:How to use replace method on multiple columns col0,col1,col2 with multiple conditons如何在具有多个条件的多列 col0、col1、col2 上使用替换方法
【发布时间】:2020-04-21 04:24:32
【问题描述】:

如何在多列 col0,col1,col2 上使用替换方法

new_df['col0'].str.replace(']]', ']')

【问题讨论】:

标签: python pandas


【解决方案1】:

使用DataFrame.replace:

new_df = pd.DataFrame({'col0':[']]','aa]]'],
                       'col1':[']]','[s]'],
                       'col2':['[[]]]]',']'],
                       'col3':[']]', '[[]]]']})
print (new_df)
   col0 col1    col2   col3
0    ]]   ]]  [[]]]]     ]]
1  aa]]  [s]       ]  [[]]]

cols = ['col0','col1','col2']
new_df[cols] = new_df[cols].replace(']]', ']')
print (new_df)
   col0 col1    col2   col3
0     ]    ]  [[]]]]     ]]
1  aa]]  [s]       ]  [[]]]

如果要替换子字符串,请添加 regex=True 并通过 \ 转义,因为 [ 是特殊的 regex 字符:

cols = ['col0','col1','col2']
new_df[cols] = new_df[cols].replace('\]\]', ']', regex=True)
print (new_df)
  col0 col1  col2   col3
0    ]    ]  [[]]     ]]
1  aa]  [s]     ]  [[]]]

编辑:如果可能,将值转换为列表:

import ast

test=pd.DataFrame({'gender':['M']*4,'B':[[['Office/Work'],['31-35'], ['Salaried']],[['Movies,Restaurants'],['21-25'], ['Salaried']],[[ 'College/Park'],['21-25'],['Student']],[['College'], ['21-25'], ['Student']]]})
test = test.astype(str)
print (test)
  gender                                                  B
0      M         [['Office/Work'], ['31-35'], ['Salaried']]
1      M  [['Movies,Restaurants'], ['21-25'], ['Salaried']]
2      M         [['College/Park'], ['21-25'], ['Student']]
3      M              [['College'], ['21-25'], ['Student']]

df = pd.DataFrame([[y[0] for y in ast.literal_eval(x)] for x in test['B']],
                   columns=['a','b','c'])
print (df)
                    a      b         c
0         Office/Work  31-35  Salaried
1  Movies,Restaurants  21-25  Salaried
2        College/Park  21-25   Student
3             College  21-25   Student

replace 的解决方案:

df = test['B'].replace(['\[\[','\]\]', '\], \['], ['', '', ';'], regex=True).str.split(';', expand=True)
print (df)
                      0        1           2
0         'Office/Work'  '31-35'  'Salaried'
1  'Movies,Restaurants'  '21-25'  'Salaried'
2        'College/Park'  '21-25'   'Student'
3             'College'  '21-25'   'Student'

【讨论】:

  • 如果我想替换,[ 需要做什么还请如何删除['
  • @ain - 你能创建一些示例数据吗,minimal, complete, and verifiable example
  • test=pd.DataFrame({'gender':['M'],'B':[[['Office/Work'],['31-35'], ['受薪']]}) > out > '办公室/工作','31-35','受薪'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-12
  • 2021-01-31
  • 2021-08-17
  • 1970-01-01
  • 2020-02-10
  • 1970-01-01
  • 2021-11-18
相关资源
最近更新 更多