[英]how to extract each numbers from pandas string column to list?
How to do that?怎么做?
I have pandas dataframe looks like:我有 pandas dataframe 看起来像:
Column_A
11.2 some text 17 some text 21
some text 25.2 4.1 some text 53 17 78
121.1 bla bla bla 14 some text
12 some text
I need to transfer this each row to separated list:我需要将每一行转移到单独的列表中:
listA[0] = 11.2 listA[1] = 17 listA[2] = 21
listB[0] = 25.2 listB[1] = 4.1 listB[2] = 53 listB[3] = 17 listB[4] = 78
listC[0] = 121.1 listC[1] = 14
listD[0] = 12
You can use re
to find all the occurrences of the numbers either integer or float.您可以使用re
查找所有出现的数字 integer 或浮点数。
df['Column_A'].apply(lambda x: re.findall(r"[-+]?\d*\.\d+|\d+", x)).tolist()
OUTPUT : OUTPUT :
[['11.2', '17', '21'], ['25.2', '4.1', '53', '17', '78'], ['121.1', '14'], ['12']]
If you want, you can type cast them to float
/ int
checking if the extracted string has .
如果需要,您可以将它们类型转换为float
/ int
检查提取的字符串是否具有.
in them, something like this:在他们中,是这样的:
df['Column_A'].apply(lambda x: re.findall(r"[-+]?\d*\.\d+|\d+", x)).map(lambda x: [int(i) if '.' not in i else float(i) for i in x]).tolist()
OUTPUT : OUTPUT :
[[11.2, 17, 21], [25.2, 4.1, 53, 17, 78], [121.1, 14], [12]]
As pointed by @Uts, we can directly call findall
over Series.str
as:正如@Uts 所指出的,我们可以直接通过Series.str
调用findall
:
listA, listB, listC, listD = df.Column_A.str.findall(r"[-+]?\d*\.\d+|\d+")
[re.findall(r"\d+?\.?\d*", x) for x in Column_A]
You'll get a list of lists for every row in that column.您将获得该列中每一行的列表列表。 It will be strings but you can convert to float however you want after that.它将是字符串,但之后您可以根据需要转换为浮点数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.