[英]split numbers and string to differents columns on pandas
我喜歡將列拆分為str
和數字。
data={"name&numb":["cat 123","34 dog","bird 93","dolphin dof 8 ","lion cat 76","tiger 22 animal "]}
df=pd.DataFrame.from_dict(data)
我這樣做所以分開數字
df["number"]=df["name&numb"].str.extract('(\d+)')
現在我想再做一列,所以我只得到字符串,我不知道它是否會影響但在原始數據中,而不是英文
就像是:
df["strings"]=df["name&numb"].str.extract('str')
我相信您需要Series.str.extract
和\D
用於非數字數據,而Series.str.strip
用於刪除尾隨空格:
df["number"]=df["name&numb"].str.extract('(\d+)')
df["strings"] = df["name&numb"].str.extract('(\D+)', expand=False).str.strip()
如果需要所有字符串,一個想法是使用:
f = lambda x: ' '.join(y for y in x.split() if not y.isdigit())
df["strings1"] = df["name&numb"].apply(f)
print (df)
name&numb number strings strings1
0 cat 123 123 cat cat
1 34 dog 34 dog dog
2 bird 93 93 bird bird
3 dolphin dof 8 8 dolphin dof dolphin dof
4 lion cat 76 76 lion cat lion cat
5 tiger 22 animal 22 tiger tiger animal
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.