【问题标题】:How to split a string and assign as column name for a pandas dataframe?如何拆分字符串并指定为熊猫数据框的列名?
【发布时间】:2018-07-12 08:40:15
【问题描述】:

我有一个数据框,它有一个这样的列:

  a;d;c;d;e;r;w;e;o
--------------------
0 h;j;r;d;w;f;g;t;r
1 a;f;c;x;d;e;r;t;y
2 b;h;g;t;t;t;y;u;f
3 g;t;u;n;b;v;d;s;e

当我拆分它时,我会变成这样:

  0  1  2  3  4  5  6  7  8
------------------------------
0 h  j  r  d  w  f  g  t  r
1 a  f  c  x  d  e  r  t  y
2 b  h  g  t  t  t  y  u  f
3 g  t  u  n  b  v  d  s  e

我需要指定a d c d e r w e o 而不是0 1 2 3 4 5 6 7 8 作为列名。

我试过了:

df = dataframe
df = df.iloc[:,0].str.split(';')
res = pd.DataFrame(df.columns.tolist())
res = pd.DataFrame(df.values.tolist())

我得到分配给每一列的值..但不是列标题。怎么办?

【问题讨论】:

    标签: python pandas dataframe series


    【解决方案1】:

    我认为需要通过expand=True 参数创建新的DataFrame,然后分配新的列名:

    res = df.iloc[:,0].str.split(';', expand=True)
    res.columns = df.columns[0].split(';')
    print (res)
       a  d  c  d  e  r  w  e  o
    0  h  j  r  d  w  f  g  t  r
    1  a  f  c  x  d  e  r  t  y
    2  b  h  g  t  t  t  y  u  f
    3  g  t  u  n  b  v  d  s  e
    

    但如果只有一列数据,可能需要read_csv 中的sep=';'

    res = pd.read_csv(file, sep=';')
    

    【讨论】:

    • 我无法添加 sep=';'在 read_csv 中。因为维度不固定
    • @qwww - 好吧,这只是想法 :)
    • 我使用了上面的代码。但它给了我长度不匹配
    • @qwww - 这意味着有更多的列名,如df,返回len(df.iloc[:,0].str.split(';', expand=True).columns)len(df.columns[0].split(';'))
    • 它给了我 38 和 32
    猜你喜欢
    • 2015-06-25
    • 2019-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    • 2018-12-04
    • 2019-04-21
    • 1970-01-01
    相关资源
    最近更新 更多