[英]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. 我需要分配
adcderweo
而不是0 1 2 3 4 5 6 7 8
作为列名。
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: 我认为需要通过
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
But maybe need sep=';'
但也许需要
sep=';'
in read_csv
if only one column data: 如果只有一列数据,则在
read_csv
:
res = pd.read_csv(file, sep=';')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.