[英]how to extract each numbers from pandas string column to list?
怎么做?
我有 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
我需要將每一行轉移到單獨的列表中:
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
您可以使用re
查找所有出現的數字 integer 或浮點數。
df['Column_A'].apply(lambda x: re.findall(r"[-+]?\d*\.\d+|\d+", x)).tolist()
OUTPUT :
[['11.2', '17', '21'], ['25.2', '4.1', '53', '17', '78'], ['121.1', '14'], ['12']]
如果需要,您可以將它們類型轉換為float
/ int
檢查提取的字符串是否具有.
在他們中,是這樣的:
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 :
[[11.2, 17, 21], [25.2, 4.1, 53, 17, 78], [121.1, 14], [12]]
正如@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]
您將獲得該列中每一行的列表列表。 它將是字符串,但之后您可以根據需要轉換為浮點數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.