[英]How to take part of string value from column in DataFrame in Python Pandas?
[英]Slice pandas dataframe by part of string value in column
我有一個 Pandas 數據框,其中包含一個帶有 9 個字符的字符串的列。 我想在數據框中找到與此字符串中 9 個字符中的前 3 個匹配的行。
我當前的解決方案在數據框中創建一個新列,它只是對字符串的前 3 個字符進行切片,但我想在不創建新列的情況下解決這個問題(因為我稍后必須刪除它)。 如果可以的話,我通常不希望更改數據框。
例子:
import pandas as pd
# sample dataframe:
cid=[1,2,3,4,5,6,7,8,9,10]
strings=[
'tncduuqcr',
'xqjfykalt',
'arzouazgz',
'tncknojbi',
'xqjgfcekh',
'arzupnzrx',
'tncfjxyox',
'xqjeboxdn',
'arzphbdcs',
'tnctnfoyi',
]
df=pd.DataFrame(list(zip(cid,strings)),columns=['cid','strings'])
# This is the step I would like to avoid doing:
df['short_strings']=df['strings'].str[0:3]
out_dict={}
for x in df['short_strings'].unique():
df2=df[df['short_strings']==x]
out_dict[x]=df2
# the separate dataframes:
for x in out_dict.keys():
print(out_dict[x])
輸出:
cid strings short_strings
0 1 tncduuqcr tnc
3 4 tncknojbi tnc
6 7 tncfjxyox tnc
9 10 tnctnfoyi tnc
cid strings short_strings
1 2 xqjfykalt xqj
4 5 xqjgfcekh xqj
7 8 xqjeboxdn xqj
cid strings short_strings
2 3 arzouazgz arz
5 6 arzupnzrx arz
8 9 arzphbdcs arz
我試過簡單地比較==df['strings'].str[0:3]
但這似乎不起作用。
對於此類操作,我們使用DataFrame.groupby()
+ GroupBy.__iter__()
,此處使用Series.unique
索引會較慢:
mydict = dict(df.groupby(df.strings.str[:3]).__iter__())
print(mydict)
輸出
{'arz': cid strings
2 3 arzouazgz
5 6 arzupnzrx
8 9 arzphbdcs,
'tnc': cid strings
0 1 tncduuqcr
3 4 tncknojbi
6 7 tncfjxyox
9 10 tnctnfoyi,
'xqj': cid strings
1 2 xqjfykalt
4 5 xqjgfcekh
7 8 xqjeboxdn}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.