V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
toyst
V2EX  ›  Python

pandas 字符串拼接问题

  •  
  •   toyst · 2022-01-21 13:59:38 +08:00 · 2302 次点击
    这是一个创建于 797 天前的主题,其中的信息可能已经有所发展或是发生改变。
    import pandas as pd
    df = pd.DataFrame(columns = ['a', 'b', 'c'],
                 data=[['A','1','http:1'],
                       ['B', '2','http:2'],
                       ['C', '3','http:3'],
                       ['D','4','http:4']])
    print(df)
    
       a  b       c
    0  A  1  http:1
    1  B  2  http:2
    2  C  3  http:3
    3  D  4  http:4
    

    我想输出:

    #Result
    G "A","1"
    http:1
    G "B","2"
    http:2
    G "C","3"
    http:3
    G "D","4"
    http:4
    

    这样的格式,应该怎么拼接输出啊

    6 条回复    2022-01-21 16:55:28 +08:00
    tfdetang
        1
    tfdetang  
       2022-01-21 14:38:20 +08:00
    这不就是行循环一下 把每列的内容放到格式化的字符串里就行了吗
    toyst
        2
    toyst  
    OP
       2022-01-21 16:35:05 +08:00
    @tfdetang 关键是这个 http:1 是个回车怎么拼接啊
    zhusimaji
        3
    zhusimaji  
       2022-01-21 16:39:33 +08:00 via iPhone
    @toyst 回车自己加个\n
    cclin
        4
    cclin  
       2022-01-21 16:45:40 +08:00 via Android
    拿去抄吧
    def combine(line: pd.Series):
    print(line)
    return f'G "{line.a}","{line.b}"\n{line.c}'


    df = df.apply(combine, axis=1)

    for s in list(df):
    print(s)
    cassidyhere
        5
    cassidyhere  
       2022-01-21 16:46:09 +08:00
    'G "' + df.a + '","' + df.b + '"\n' + df.c
    toyst
        6
    toyst  
    OP
       2022-01-21 16:55:28 +08:00
    感谢大家,原来输出到文本\n 就能显示换行符了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2427 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 16:05 · PVG 00:05 · LAX 09:05 · JFK 12:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.