如何在熊猫中将字符串列转换为字符串列表列的列表

时间:2020-04-08 01:23:16

标签: python pandas

我有一个这样的熊猫数据框:

import ConsoleCommandParserTypes from "./ConsoleCommandParserTypes";

export abstract class ConsoleCommandsParser {

  public static parse(arrayedConsoleCommand: Array<string>): void {
    // not implemented yet
  }
}

// Invalid syntax
export namespace ConsoleCommandParserTypes as ConsoleCommandParser;
// Namespace can not be used as value
export ConsoleCommandParser = ConsoleCommandParserTypes 
// Invalid syntax
export namespace ConsoleCommandParser = ConsoleCommandParserTypes;

我想将该列转换为如下所示的字符串列表列:

df = pd.DataFrame ({'names': ['John;Joe;Tom', 'Justin', 'Ryan;John']})

    names
0   John;Joe;Tom
1   Justin
2   Ryan;John

我做了以下事情:

0    ['John', 'Joe', 'Tom']
1            ['Justin']
2        ['Ryan', 'John']

我得到的是:

df.names.apply(lambda x: x.split(';'))

我把所有引号都弄丢了。有谁知道该如何解决?非常感谢。

2 个答案:

答案 0 :(得分:2)

您永远不会丢失引号。 只是因为大熊猫没有显示两行或更多行的引号。 检查以下示例。

df = pd.DataFrame ({'names': ['John;Joe;Tom', 'Justin', 'Ryan;John']})
df.names = df.names.apply(lambda x: x.split(';'))
df.names.iloc[0]

您的输出为['John', 'Joe', 'Tom']

答案 1 :(得分:0)

正如Gilseung所说,输出与您的输出相同。但是,如果您真的坚持在输出中添加引号作为额外的字符,请尝试以下操作:

def add(x):
    temp_list = x.split(';')
    temp_list = [f"\'{x}\'" for x in temp_list]       #adds extra character
    return temp_list

df = df.names.apply(add)

为您提供以下输出:

0    ['John', 'Joe', 'Tom']
1                ['Justin']
2          ['Ryan', 'John']
Name: names, dtype: object
相关问题