如何将单行转换为带有标题的jupyter笔记本中的四个不同列?

问题描述 投票:1回答:1

我有excel文件是一行。我导入了jupyter笔记本,Iam试图在jupyter笔记本中使用pandas创建这一行的四列。例如行:

姓名:查尔斯

电子邮件:[email protected]

键:10223209asd

摘要:这是一个例子

名称:大脑

电子邮件:[email protected]

关键:10390weq09asd

摘要:这是一个例子

我希望列中的每一行都有这样的信息。

4列:名称电子邮件密钥摘要

第1行:姓名:charles email:[email protected] key:10223209asd摘要:这是一个..

我还有第二个文件。如何取两行并将它们分成两列标题。

电子邮件:[email protected]

info:这是一封电子邮件的示例。这不仅仅是句子长。

电子邮件:[email protected]

info:这是一封电子邮件的示例。这不仅仅是句子长。

我希望列中的内容与2列电子邮件和信息中的信息一样。

string pandas parsing jupyter-notebook rows
1个回答
0
投票

使用reshapeDataFrame构造函数:

print (df)
                           col
0                name: charles
1        email: [email protected]
2             key: 10223209asd
3  summary: this is an example
4                  name: brain
5        email: [email protected]
6           key: 10390weq09asd
7  summary: this is an example

cols = ['name','email','key','summary']
df1 = pd.DataFrame(df['col'].values.reshape(-1, 4), columns=cols)
print (df1)
            name                  email                 key  \
0  name: charles  email: [email protected]    key: 10223209asd   
1    name: brain  email: [email protected]  key: 10390weq09asd   

                       summary  
0  summary: this is an example  
1  summary: this is an example  

如果想在:之前删除值

cols = ['name','email','key','summary']
df2 = pd.DataFrame(df['col'].str.split(':\s+').str[1].values.reshape(-1, 4), columns=cols)
print (df2)
      name           email            key             summary
0  charles  [email protected]    10223209asd  this is an example
1    brain  [email protected]  10390weq09asd  this is an example

一般的解决方案是通过DataFrame创建str.split,然后通过cumcount计算重复数,并通过unstack重新计算:

df2 = df['col'].str.split(':\s+', expand=True)
df2.columns = ['key','val']

df2 = df2.set_index([df2.groupby('key').cumcount(), 'key'])['val'].unstack()
print (df2)
key           email            key     name             summary
0    [email protected]    10223209asd  charles  this is an example
1    [email protected]  10390weq09asd    brain  this is an example
© www.soinside.com 2019 - 2024. All rights reserved.