【问题标题】:Replacing column data with Pandas .replace not working用 Pandas .replace 替换列数据不起作用
【发布时间】:2019-08-01 00:38:10
【问题描述】:

我正在尝试将data from a .csv 变成 Pandas df:

df = pd.read_csv('congress1.csv', delimiter = ';', names = ['Name', 'Years', 'Position', 'Party', 'State', 'Congress'], header = 0)

我想用单个日期 - “1789”替换“国会”列 - “1(1789-1790)”中的数据:

df['Congress'] = df['Congress'].replace('1(1789-1790)', '1789')

但是,这样做不会更改我的任何数据。如果我说,包括 inplace=True

df['Congress'] = df['Congress'].replace('1(1789-1790)', '1789', inplace=True)

...我在该列中的数据当然会变为空。然而我似乎无法用任何有意义的东西替换这个字符串。

【问题讨论】:

  • 请查看@Willem 的答案,但是您不需要inplace=true,因为您将其分配回df['Congress'] 列,因此它将被放置!如果您正在寻找单个实例,那么如果您希望将其替换为所有日期的 Congress,那么您需要一个正则表达式。

标签: python pandas


【解决方案1】:

这里有两个问题:

  1. 您应该使用.str 部分将列“解释”为字符串;和
  2. 您需要转义括号。
df['Congress'] = df['Congress']<b>.str</b>.replace(<b>r</b>'1<b>\</b>(1789-1790<b>\</b>)', '1789')

所以我们将字符串部分替换为1789。

【讨论】:

  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 2021-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-28
  • 1970-01-01
  • 1970-01-01
  • 2016-08-20
相关资源
最近更新 更多