【问题标题】:Changes csv row value更改 csv 行值
【发布时间】:2021-12-24 15:26:36
【问题描述】:

这是我的代码:


import pandas as pd
import re

# reading the csv file
patients = pd.read_csv("partial.csv")
  
# updating the column value/data
for patient in patients.iterrows():
    cip=patient['VALOR_ID']
    new_cip = re.sub('^(\w+|)',r'FIXED_REPLACED_STRING',cip)
    patient['VALOR_ID'] = new_cip
  
# writing into the file
df.to_csv("partial-writer.csv", index=False)
  
print(df)

我收到了这条消息:

Traceback(最近一次调用最后一次): 文件“/home/jeusdi/projects/workarea/salut/load-testing/load.py”,第 28 行,在 cip=患者['VALOR_ID'] TypeError: 元组索引必须是整数或切片,而不是 str

编辑 上面的表单代码你可以认为我需要为所有行设置一个相同的固定值。

我需要遍历“行”并生成一个随机字符串并将其设置在每个不同的“行”上。

上面的代码是:

for patient in patients.iterrows():
    new_cip = generate_cip()
    patient['VALOR_ID'] = new_cip

【问题讨论】:

  • 你能添加一些数据样本来提问吗?

标签: python-3.x pandas csv


【解决方案1】:

在正则表达式中使用Series.str.replace,但不确定|。也许应该删除它:

df = pd.read_csv("partial.csv")

df['VALOR_ID'] = df['VALOR_ID'].str.replace('^(\w+|)',r'FIXED_REPLACED_STRING')

#if function return scalars
df['VALOR_ID'] = df['VALOR_ID'].apply(generate_cip)

df.to_csv("partial-writer.csv", index=False)

【讨论】:

  • 你可以跳过循环,用那一行替换整个列,在 Pandas 中?
  • @ZachYoung - 完全正确。这是从 Q 中添加第一行和最后一行代码的原因。
  • 我需要生成一个随机字符串来替换。我的意思是,我需要每个“单元格值”在“转换”之后都有不同的值。你能提供一种迭代“行”的方法吗?我正在编辑帖子以获取更多详细信息。非常感谢您的帮助。
  • @Jordi - 你可以试试df['VALOR_ID'] = df['VALOR_ID'].apply(generate_cip) 吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-04
  • 2017-06-05
  • 2021-03-08
  • 1970-01-01
  • 2019-11-21
  • 1970-01-01
相关资源
最近更新 更多