python - 用 Pandas .replace 替换列数据不起作用

标签 python pandas

我正在尝试转动 data from a .csv进入 Pandas df:

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

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

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

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

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

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

最佳答案

这里有两个问题:

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

因此我们将字符串部分替换为1789

关于python - 用 Pandas .replace 替换列数据不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53141072/

相关文章:

python - 按字母顺序列出动物以及哪种动物打败谁

python : How to easily track the module/function definition in big package

python - 附加现有进程以获取成功或失败命令?

python - Pandas :如何将 df 与条件合并

python - 使用python从列表中提取Json数据

python - 获得最佳解决方案之后的下一个最佳解决方案

python - 获取包含所有所需值的组

python - 使用 SQLAlchemy、to_sql 使用 pandas 写入 MySQL 数据库

python - 特定格式的数据框枢轴

python - 如何创建没有 'date' 部分的日期时间列?