推荐学习书目
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 · Jan 21, 2022 · 3172 views
    This topic created in 1583 days ago, the information mentioned may be changed or developed.
    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 replies    2022-01-21 16:55:28 +08:00
    tfdetang
        1
    tfdetang  
       Jan 21, 2022
    这不就是行循环一下 把每列的内容放到格式化的字符串里就行了吗
    toyst
        2
    toyst  
    OP
       Jan 21, 2022
    @tfdetang 关键是这个 http:1 是个回车怎么拼接啊
    zhusimaji
        3
    zhusimaji  
       Jan 21, 2022 via iPhone
    @toyst 回车自己加个\n
    cclin
        4
    cclin  
       Jan 21, 2022 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  
       Jan 21, 2022
    'G "' + df.a + '","' + df.b + '"\n' + df.c
    toyst
        6
    toyst  
    OP
       Jan 21, 2022
    感谢大家,原来输出到文本\n 就能显示换行符了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2765 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 75ms · UTC 10:18 · PVG 18:18 · LAX 03:18 · JFK 06:18
    ♥ Do have faith in what you're doing.