在python中从 Dataframe 中删除[]

cs7cruho  于 2022-12-21  发布在  Python
关注(0)|答案(3)|浏览(184)

我有一个带有[]的 Dataframe
我想从"名称"列中删除[]
我试过这个:

df['Name'] = df['Name'].str.replace("['", "")
df['Name'] = df['Name'].str.replace("']", "")

但是好像不起作用

fxnxkyjh

fxnxkyjh1#

你的列由列表组成,而不是字符串,所以你不能对它使用字符串操作。你 * 可以 *(并且应该)做的是将字符串列表.join为用逗号分隔的字符串。

>>> df = pd.DataFrame({'Test': [['foo', 'bar'], ['baz']]})
>>> df
         Test
0  [foo, bar]
1       [baz]
>>> df.dtypes
Test    object
dtype: object
>>> df['Test'] = df.Test.str.join(',')
>>> df
      Test
0  foo,bar
1      baz
pkln4tw6

pkln4tw62#

代码中有错误,即'(单引号)字符。请尝试以下操作:

import pandas as pd

df = pd.DataFrame.from_records(data=[
    {
        "Name": "[Name1]",
        "ID": 1
    },
    {
        "Name": "[Name2]",
        "ID": 2
    },
        {
        "Name": "[Name3]",
        "ID": 3
    }
])

print(df)
df['Name'] = df['Name'].str.replace("[", "")
df['Name'] = df['Name'].str.replace("]", "")
print(df)

返回:

Name  ID
0  [Name1]   1
1  [Name2]   2
2  [Name3]   3
/home/sawik/./playground.py:81: FutureWarning: The default value of regex will change from True to False in a future version. In addition, single character regular expressions will *not* be treated as literal strings when regex=True.
  df['Name'] = df['Name'].str.replace("[", "")
/home/sawik/./playground.py:82: FutureWarning: The default value of regex will change from True to False in a future version. In addition, single character regular expressions will *not* be treated as literal strings when regex=True.
  df['Name'] = df['Name'].str.replace("]", "")
    Name  ID
0  Name1   1
1  Name2   2
2  Name3   3
xxls0lw8

xxls0lw83#

这应该有帮助,你需要使用字符来解决问题

string = '[ads[123['
print(string.replace('[', '').replace(']', ''))

相关问题