简体   繁体   English

Python将列表转换为数据框中的字符串

[英]Python convert list to string in the dataframe

I have bunch of list and string like texts in the cell value of the pandas data frame.我在熊猫数据框的单元格值中有一堆列表和字符串,如文本。 I am trying to convert list to string, I am able to convert list to string, but its splitting the string as well.我正在尝试将列表转换为字符串,我可以将列表转换为字符串,但它也会拆分字符串。 How do I only apply this logic if the cell contains list [] in the particular column?如果单元格在特定列中包含列表 [],我如何仅应用此逻辑?

raw_data = {'Name': [['\'John Smith\''], ['\'Jane Doe\'']],
        'id': [['\'A1005\'','\'A1006\''], 'A200,A400,A500']}
dfRaw = pd.DataFrame(raw_data, columns = ['Name','id'])
dfRaw['Name'] = dfRaw['Name'].astype(str)

Data数据

Name                    id
0   ["'John Smith'"]    ['A1005', 'A1006']
1   ["'Jane Doe'"]  A200,A400,A500

Need output like this:需要这样的输出:

    Name                id
0   ["'John Smith'"]    'A1005','A1006'
1   ["'Jane Doe'"]      A200,A400,A500

But the code below is splitting string cell values too.但下面的代码也在拆分字符串单元格值。

dfRaw['id'] = dfRaw['id'].apply(lambda x: ','.join([str(i) for i in x]))

Name                     id
0   ["'John Smith'"]    'A1005','A1006'
1   ["'Jane Doe'"]  A,2,0,0,,,A,4,0,0,,,A,5,0,0

You could use a list comprehension to generate a new list with the rows in id joining those entries that are lists using string.join .您可以使用列表string.join生成一个新列表,其中id的行使用string.join连接那些列表条目。 You can check if an entry is a list using isinstance :您可以使用isinstance来检查条目是否为list

df['id'] = [','.join(i) if isinstance(i, list) else i for i in df['id']]

Output输出

       Name                    id
0  ['John Smith']          A1005,A1006
1    ['Jane Doe']        A200,A400,A500

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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