如何将字符串表示列表与混合值转换为列表?



如何转换包含字符串和数字值的字符串,给定列表中的字符串不在引号中?

import pandas as pd
df = pd.DataFrame({'col_1': ['[2, A]', '[5, BC]']})
print(df)
col_1
0   [2, A]
1  [5, BC]
col_1    [2, A]
Name: 0, dtype: object

我的目标是在另一个函数中使用列表,所以我尝试用内置函数(如eval()或ast.literal_eval())转换字符串,但是在这两种情况下,我都需要在字符串周围添加引号,所以它是"one_answers"BC".

您可以首先使用regex在可能的字符串周围添加引号(这里我使用字母+下划线),然后使用literal_eval(由于某种原因,我使用pd.eval有错误)

from ast import literal_eval
df['col_1'].str.replace(r'([a-zA-Z_]+)', r'"1"', regex=True).apply(literal_eval)

输出(列表):

0     [2, A]
1    [5, BC]

它已经是一个字符串,如果数据将以某种格式-

df['col_2'] = df['col_1'].apply(lambda x: x.split(',')[1].rstrip(']'))

如果您希望输出为列表:

import pandas as pd
df = pd.DataFrame({'col_1': ['[2, A]', '[5, BC]']})
print(df)
a = df["col_1"].to_list()
actual_list = [[int(i.split(",")[0][1:]), str(i.split(",")[1][1:-1])] for i in a]
actual_list

输出:

[[2, 'A'], [5, 'BC']]

如果您只需要将字符串表示列表转换为字符串列表,则可以将str.strip()str.split()结合使用,如下所示:

df['col_1'].str.strip('[]').str.split(',s*')

结果:

print(df['col_1'].str.strip('[]').str.split(',s*').to_dict())
{0: ['2', 'A'], 1: ['5', 'BC']}

如果您想进一步将数值字符串转换为数字,您可以进一步使用pd.to_numeric(),如下所示:

df['col_1'].str.strip('[]').str.split(',s*').apply(lambda x: [pd.to_numeric(y, errors='ignore') for y in x])

结果:

print(df['col_1'].str.strip('[]').str.split(',s*').apply(lambda x: [pd.to_numeric(y, errors='ignore') for y in x]).to_dict())
{0: [2, 'A'], 1: [5, 'BC']}           # 2, 5 are numbers instead of strings

最新更新