我有一个pandas dataframe,其中包含一个包含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],但这似乎不起作用。
发布于 2020-11-10 02:44:54
对于这种类型的操作,我们使用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}https://stackoverflow.com/questions/64757400
复制相似问题