【问题标题】:How to append data from one CSV column to another in Python如何在 Python 中将数据从一个 CSV 列附加到另一列
【发布时间】:2020-05-21 22:28:02
【问题描述】:

我有以下 CSV 文件输出:

Customer,Misc
customer1,business-dns-test2
customer2,dns-test2
customer1,dns-test1

当前的目标是仅当单词出现在Misc 下的同一行中时,才附加customer1 字符串-business。

也就是说,我正在寻找最终的 CSV 输出为:

Customer,Misc
customer1-business,dns-test2
customer2,dns-test2
customer1,dns-test1

本质上,这里的关键字是business。我需要确保 customer1 和 customer1-business 被视为不同的客户,尽管他们共享相同的名称 customer1。

想法?

【问题讨论】:

  • 到目前为止你尝试过什么?对于标准库的 csv 模块来说,这似乎是一项工作,需要进行一些简单的字典和字符串操作。
  • 您是否还要从第二个字段中删除business?这就是您在示例中所拥有的...

标签: python pandas csv export-to-csv


【解决方案1】:

我们可以的

df.loc[df.Misc.str.startswith('business'),'Customer']+='-business'
df.Misc=df.Misc.str.strip('business-')
df
Out[93]: 
             Customer       Misc
0  customer1-business  dns-test2
1           customer2  dns-test2
2           customer1  dns-test1

【讨论】:

    猜你喜欢
    • 2019-07-11
    • 2012-03-02
    • 1970-01-01
    • 2018-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-19
    • 1970-01-01
    相关资源
    最近更新 更多