简体   繁体   中英

How to split a string and assign as column name for a pandas dataframe?

I have a dataframe which has a single column like this:

  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

When I split it I am getting like this:

  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

I need to assign adcderweo instead of 0 1 2 3 4 5 6 7 8 as column names.

I tried :

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

I am getting values assigned to each column..But not column headers. What to do?

I think need create new DataFrame by expand=True parameter and then assign new columns names:

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

But maybe need sep=';' in read_csv if only one column data:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM