• 请不要在回答技术问题时复制粘贴 AI 生成的内容
hujianxin
V2EX  ›  程序员

pandas read_csv 如何指定部分(前 n 个)seperator

  •  
  •   hujianxin · Jan 25, 2019 · 1938 views
    This topic created in 2688 days ago, the information mentioned may be changed or developed.

    比如我的 csv 文件是这样的

    age,first_name,other
    12,hello,world,john
    13,hi,csv,lili
    

    如上面所示,第一行有使用逗号分割了三个元素,第二、三行使用逗号分割了四个元素。

    现在需求是通过 pandas 读入 csv 文件,成为一个 Dataframe,形式如下:

    age   first_name     other
    12    hello          world,join
    13    hi             csv,lili
    

    这种需求 pandas 能实现吗?希望使用过的大佬可以帮忙解惑,多谢!

    1 replies    2019-01-26 00:00:21 +08:00
    habin
        1
    habin  
       Jan 26, 2019
    可以的,other 是 world、csv 的表头,john,lili 没有表头的通过读取后可以直接字符串连接
    data = pd.read_csv('1.csv')
    data['other'] = data['other'] +',' +data['Unnamed: 3'] # 'Unnamed: 3'为 john、lili 的表头
    data.drop('Unnamed: 3',axis = 1,inplace = True)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2708 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 15:18 · PVG 23:18 · LAX 08:18 · JFK 11:18
    ♥ Do have faith in what you're doing.