此完整代码将提供您所期望的。
必须有很多方法可以改进此代码。为了提高您的技能,我强烈建议您遵循代码的工作原理。然后,您将能够根据需要编辑此代码:)
import pandas as pd
df1 = pd.DataFrame(
{
'name': ['raddit', 'dog', 'squirrel', 'cat', 'donkey', 'missing',],
'product': ['carrot', 'bone', 'carrot', 'milk', 'missing', 'meat',],
}
)
df2 = pd.DataFrame(
{
'id': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,],
'name_product': ['milk', 'bone', 'carrot', 'raddit', 'dog', 'cat', 'cat', 'dog', 'dog', 'raddit', 'donkey', 'donkey', 'squirrel',],
'type': ['attribute', 'attribute', 'attribute', 'attribute', 'attribute', 'attribute', 'attribute', 'attribute', 'attribute', 'attribute', 'attribute', 'attribute', 'attribute',],
'source': ['NaN', 'NaN', 'NaN', 'NaN', 'NaN', 'NaN', 'NaN', 'NaN', 'NaN', 'NaN', 'NaN', 'NaN', 'NaN'],
'target': ['NaN', 'NaN', 'NaN', 'NaN', 'NaN', 'NaN', 'NaN', 'NaN', 'NaN', 'NaN', 'NaN', 'NaN', 'NaN'],
}
)
# to make animal-feed dictionary
feed = dict()
for i, row in df1.iterrows():
if row['product'] in feed.keys():
feed[row['product']].append(row['name'])
else:
feed[row['product']] = [row['name']]
# df3 is for only results
df3 = pd.DataFrame(columns=['id', 'name_product', 'type', 'source', 'target'])
# to find all the rows using animal-feed dictionary
for i, row in df2.iterrows():
if row['name_product'] in feed.keys():
animals = feed[row['name_product']]
animal_id_list = df2[df2['name_product'].isin(animals)]['id'].to_list()
for animal_id in animal_id_list:
df3 = df3.append({'id': f"{row['id']},{animal_id}", 'type': 'transition', 'source': row['id'], 'target': animal_id}, ignore_index=True)
else:
pass
df3 = df2.append(df3, ignore_index=True)
print(df3)
"""
id name_product type source target
0 1 milk attribute NaN NaN
1 2 bone attribute NaN NaN
2 3 carrot attribute NaN NaN
3 4 raddit attribute NaN NaN
4 5 dog attribute NaN NaN
5 6 cat attribute NaN NaN
6 7 cat attribute NaN NaN
7 8 dog attribute NaN NaN
8 9 dog attribute NaN NaN
9 10 raddit attribute NaN NaN
10 11 donkey attribute NaN NaN
11 12 donkey attribute NaN NaN
12 13 squirrel attribute NaN NaN
13 1,6 NaN transition 1 6
14 1,7 NaN transition 1 7
15 2,5 NaN transition 2 5
16 2,8 NaN transition 2 8
17 2,9 NaN transition 2 9
18 3,4 NaN transition 3 4
19 3,10 NaN transition 3 10
20 3,13 NaN transition 3 13
"""