python - 使用所需重复列表将重复行插入到 DataFrame

标签 python pandas

我正在尝试使用另一个数据框的索引复制一个数据框。例如,假设如下:

basket = pd.DataFrame(columns = ["food_type", "food", "qty"], data=[
    ["fruit" ,  "apple",   1],
    ["fruit" ,  "pear",    1],
    ["fruit" ,  "banana",  1],
    ["veggie",  "carrot",  1],
    ["veggie",  "lettuce", 1]])

basket.set_index(["food_type", "food"], inplace=True)

enter image description here

我正在尝试使用人员列表复制这些行,以便实现以下目标:

target_df = pd.DataFrame(columns = ["person", "food_type", "food", "qty"]
                        ).set_index(["person", "food_type", "food"])

people = ["jane", "john", "joan"]
for person in people:
    basket_copy = basket.copy()
    basket_copy["person"] = person
    basket_copy.set_index("person", append=True, inplace=True)
    target_df = target_df.append(basket_copy)

enter image description here

此解决方案有效但看起来很笨重。在 Python 中有更自然的方法吗?我在想象 basket 数据框和 people 数组之间的某种合并。

最佳答案

你可以结合concat , assign , 和 set_index :

df = pd.concat(basket.assign(person=p) for p in people).set_index('person', append=True)

结果输出:

                          qty
food_type food    person     
fruit     apple   jane      1
          pear    jane      1
          banana  jane      1
veggie    carrot  jane      1
          lettuce jane      1
fruit     apple   john      1
          pear    john      1
          banana  john      1
veggie    carrot  john      1
          lettuce john      1
fruit     apple   joan      1
          pear    joan      1
          banana  joan      1
veggie    carrot  joan      1
          lettuce joan      1

关于python - 使用所需重复列表将重复行插入到 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42938072/

相关文章:

python - 使用 python 增量解析大型维基百科转储 XML 文件

python - 如何循环遍历循环列表,同时查看当前元素的前后?

python - 有没有办法从多个字典中访问具有相同名称的键?

python - 使用 Python 从一系列列表中选择项目

python - 将平均列添加到 Pandas 多索引数据框中

python - 如何使用 sqlalchemy 打印 MySQL 列

python - 根据长度列表创建新变量

python - cartopy set_xlabel set_ylabel(不是刻度标签)

python - 比较 pandas 中两个数据框中的元素

python - 如何按日期范围和类别对 Pandas 进行分类?