【问题标题】:Manipulating DataFrames with loops使用循环操作 DataFrame
【发布时间】:2022-01-22 00:44:49
【问题描述】:

数据说明: 我有两个数据框。 第一个 DataFrame 包含名称和产品 第二个数据框包含 ID、Name_Product、Type、Source、Target。

在识别第一个数据帧的模式后,使用第二个 df 的 ID 映射和馈送源和目标

My First DataFrame

Second DataFrame:

How do I get an Expected Updated DataFrame like this?

【问题讨论】:

  • 目前还不清楚您希望如何准确地放入“源”和“目标”列。在第三张图片中,“Source”和“Target”仍然是 NaN。另外,第一个数据框没有“目标”列,这是“产品”的错字吗?
  • 我在我的第二个数据框中有它。我只想映射属性并将它们的 id 存储在源和目标中。
  • 啊,我明白了。第三个数据框还包括第二个数据框,所以我很困惑。
  • 第二个数据框应该更新,其中Type=Transition。如果它在我的源和目标中包含 Nan 没问题
  • 在第三个数据帧中,13 行和 14 行相同(ID:1,6)。如何/为什么可以生成重复的行?

标签: python pandas dataframe loops for-loop


【解决方案1】:

此完整代码将提供您所期望的。 必须有很多方法可以改进此代码。为了提高您的技能,我强烈建议您遵循代码的工作原理。然后,您将能够根据需要编辑此代码:)

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
"""

【讨论】:

  • 这行得通,但是有没有办法只更新第二个数据帧,而不是创建第三个数据帧?
  • @Hank 因为我在for loop 中使用了df2,所以在for loop 结束之前无法实时更新df2。这就是为什么我使用额外的数据框 df3 来仅保存结果部分并将其附加到 df2。但实际上,技术上可行,但需要额外处理。我想把它当作你自己的。
  • 我试过你的代码,它工作。不知道为什么,但我无法使用我的数据框将兔子映射到胡萝卜。尝试调试代码
  • @Hank 哦,天哪……我的代码有错字,raddit……应该是兔子。对不起?
猜你喜欢
  • 2019-04-12
  • 2014-05-28
  • 1970-01-01
  • 2013-08-15
  • 2012-06-01
  • 2018-01-22
  • 2019-03-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多