Skip to main content
 首页 » 编程设计

python之对列表的一列字符串进行操作

2025年05月04日20Renyi-Fan

我正在 python 上用 pandas 开发一个项目。我收到一个像这样的 .csv 文件作为输入:

Name,Time,Data 
A,5.6,"[1,2,3]" 
A,1.2,"[1.4,3,8.9]" 
... 
B,3.4,"[0.2,3,5.1]" 
ecc.. 

(I have thousand of datas for everyname and like 10 names). So in pandas the table is:

Name   Time       Data 
A       5.6      [1,2,3] 
A       1.2      [1.4,3,8.9] 
...       
B       3.4      [0.2,3,5.1] 
... 

I need to convert to another measure unit all the numbers of the list in the "Data" column (so basically, mutiply every number of the list by a scalar). I'm having problems because, in the csv that i receive, the datas are saved as strings. So firstly i've to convert the string to a list of floats, then multiply the 3 numbers in the list for a scalar (e.g. 2) and then convert again the list into a string.

I know that performing an operation on a whole column is like:

df['Data'] = df['Data'].apply(lambda x: x*2) 

我可以用这种方式将列表“a”的每个数字相乘:

[x*2 for x in a] 

我可以用 ast 将字符串转换成列表:

a = ast.literal_eval(a) # (and with a = str(a).strip('[]') i can return to the string) 

但我无法将这三件事结合起来。

你有什么解决办法吗? (不一定使用我在这里尝试过的相同方法)。 提前致谢!

请您参考如下方法:

我建议首先使用 ast.literal_eval 将所有内容转换为列表:

import pandas as pd 
 
df = pd.DataFrame({ 
    'Name': ['A', 'A'], 
    'Time': [5.6, 1.2], 
    'Data': ["[1, 2, 3]", "[1.4, 3, 8.9]"] 
}) 
 
import ast 
 
df['Data'] = df['Data'].apply(ast.literal_eval) 

然后你就可以使用常规的列表操作了:

df['Data'] = df['Data'].apply(lambda x: [i*2 for i in x]) 
print(df['Data']) 

输出:

0         [2, 4, 6] 
1    [2.8, 6, 17.8] 
Name: Data, dtype: object 

编辑:

要将系列转换回字符串,只需再次使用 apply:

df['Data'] = df['Data'].apply(str) 

虽然我不会真的建议这样做 - 将列表存储为列表而不是字符串表示形式要方便得多。如果您想继续使用列表操作,最好将其保留为列表。