【问题标题】:Add column 0 value to different column and add text to that cell将第 0 列的值添加到不同的列并将文本添加到该单元格
【发布时间】:2021-08-27 22:21:29
【问题描述】:

我有一个包含多行多列的 csv 文件。有时文本“标记”会出现在文件中,有时不会。我需要一个代码,将“标记”文本替换为第一行的值加上一个附加字符串。下面的代码显示了我正在尝试做的事情,但它并没有像我希望的那样工作。我相信 pandas 可以做到,但我不是很熟悉。

   import csv
   with open(os.getcwd()+f'\\DeleteMe.csv', 'r') as f1:
       input = f1.read()
       for row in input:
           input=input.replace('markers', row[0] + ' text')
       with open(os.getcwd()+f'\\Final.csv', "w") as f1:
           f1.write(input)

CSV 输入示例(无标题):

title1 1 2 markers 3 4
title2 1 2
title3 1 2 markers 3 4

CSV 输出示例(我正在尝试做的):

title1 1 2 title1 text 3 4
title2 1 2
title3 1 2 title3 text 3 4

这个阶段有空白没关系。只需要将标题添加到出现“标记”的列中。我的程序稍后会清理空白,因此 csv 很好而且整洁。

在 Windows 上使用 Python 3

提前致谢

【问题讨论】:

    标签: python-3.x pandas csv


    【解决方案1】:

    你可以试试这个:

    import pandas as pd
    
    # Toy dataframe
    df = pd.DataFrame(
        {
            "0": [
                "title1",
                "title2",
                "title3",
            ],
            "1": [1, 1, 1],
            "2": [2, 2, 2],
            "3": ["markers", "", "markers"],
            "4": [3, "", 3],
            "5": [4, "", 4],
        }
    )
    
    # Filter df
    df.loc[df["3"] == "markers", "3"] = df.loc[df["3"] == "markers", "0"]
    
    # Add new values
    df["3"] = pd.Series([f"{value} text" if value else "" for value in df["3"].values])
    
    print(df)
    # Outputs
            0  1  2            3  4  5
    0  title1  1  2  title1 text  3  4
    1  title2  1  2
    2  title3  1  2  title3 text  3  4
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-05
      • 1970-01-01
      • 2017-04-04
      • 1970-01-01
      相关资源
      最近更新 更多