【问题标题】:How to perform string replace operation using pandas in python?如何在 python 中使用 pandas 执行字符串替换操作?
【发布时间】:2015-09-23 12:05:42
【问题描述】:

我有一个 Pandas 数据框,其中 Items 列是一个列表。

cust_id   Items
100     ['item1','item2','item3']
101     ['item5','item8','item9']
102     ['item2','item4']

我想把上面的数据框转换成下面的格式。

cust_id  Items
100     item1 item2 item3
101     item5 item8 item9
102     item2 item4

我尝试使用 pandas 内置的字符串替换功能将其返回原始列而不实际执行字符串替换操作。

df['Items']=(df['Items'].astype(str)).replace({"['":"", "', '":" ", "']":"" },method='string')

请指教

更新:

我使用下面的代码来创建原始数据框。

df=df1.groupby(['cust_id'])['Items'].apply(list).reset_index()

【问题讨论】:

  • 对不起是元素列表还是列表的字符串?您可以发布代码来构建您的 df 以避免歧义
  • 为什么不在列上使用apply,并执行lambda lst: ' '.join(lst)之类的操作
  • @EdChum 我已添加代码来重建我的原始 df。
  • @Brian 这对我来说是新信息,我会检查一下。

标签: python string pandas dataframe


【解决方案1】:

如果元素真的是 list ,那么你可以在列表中使用 str.join()series.apply 方法。示例 -

In [159]: df = pd.DataFrame([[100,['item1','item2','item3']],[101,['item5','item8','item9']],[102,['item2','item4']]],columns=['cust_id','Items'])

In [160]: df
Out[160]:
   cust_id                  Items
0      100  [item1, item2, item3]
1      101  [item5, item8, item9]
2      102         [item2, item4]

In [161]: df['Items'] = df['Items'].apply(' '.join)

In [162]: df
Out[162]:
   cust_id                Items
0      100    item1 item2 item3
1      101    item5 item8 item9
2      102          item2 item4

【讨论】:

  • 你可以在这里使用df['Items'].apply(' '.join)`
  • apply 函数中的 ' ' 是什么意思?
  • @mrcet007 是空间,在不同元素之间使用。
  • 谢谢!有人还可以解释为什么 pd.replace 不起作用 7 我尝试的代码有什么问题?
  • 因为 series.replace() 用于替换整个值,所以您真正想要使用的是 series.str.replace() 。但是在那里你不能使用dict,你必须提供一个正则表达式或多个.str.replace()
猜你喜欢
  • 2020-04-15
  • 1970-01-01
  • 2015-05-31
  • 2013-05-07
  • 1970-01-01
  • 2020-03-23
  • 1970-01-01
  • 2019-05-29
  • 1970-01-01
相关资源
最近更新 更多