简体   繁体   English

根据 Python 中的计数列将 DataFrame 列扩展为多行

[英]Expand DataFrame column into multiple rows based on a count column in Python

The dataframe I have: dataframe 我有:

import pandas as pd
d = pd.DataFrame({"name" : ["John", "Eric"], 
                  "days" : [1,3]})

How can I get the following data frame?如何获得以下数据框?

在此处输入图像描述

Thanks for any suggestions!感谢您的任何建议!

This for loop should suffice:这个 for 循环应该足够了:

import pandas as pd

d = pd.DataFrame({"name" : ["John", "Eric"],
                  "days" : [1,3]})

for i, num in enumerate(d['days'].values):
    for j in range(num-1):
        d = d.append(d.iloc[i], ignore_index=True)

d = d.sort_values('name', ascending=False)

Output: d Output: d

   name  days
0  John     1
1  Eric     3
2  Eric     3
3  Eric     3

Explanation:解释:

  1. Iterate through values num in the column name also get the each of current row using enumerate function遍历列中的值num还使用enumerate function 获取当前行中的每一行
  2. Append current row to the Dataframe ' num-1 ' times, ignore_index argument is set to False so that the index is not duplicated Append 当前行到Dataframe ' num-1 ' 次, ignore_index参数设置为False以便索引不重复
  3. Use .sort_values(<column name>) to in the desired使用.sort_values(<column name>)在所需的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将 Pandas DataFrame 列扩展为多行 - Expand pandas DataFrame column into multiple rows 如何根据列值 python 标记多个 dataframe 行 - How to flag multiple dataframe rows based on a column value python 如何基于python中的多个条件计算列中的唯一行 - How to count unique rows in a column based on multiple conditions in python Python:根据多个动态列值过滤数据框行 - Python : Filter dataframe rows based on multiple dynamic column values 如何根据列的值扩展 DataFrame 行? - How to expand DataFrame rows based on a column's value? 在 Pandas 中,根据同一 DataFrame 中的值对匹配多个条件的行进行计数,并将计数添加到列中 - In Pandas, count rows that match multiple criteria based on values within the same DataFrame, and add the count in column Python DataFrame:基于另一列的出现次数 - Python DataFrame: count of occurances based on another column Python 数据框 - 基于列删除连续行 - Python dataframe - drop consecutive rows based on a column Python DataFrame - Select dataframe rows based on values in a column of same dataframe - Python DataFrame - Select dataframe rows based on values in a column of same dataframe 根据其他行和列的多个条件在数据框中创建新列? 包括空行? - 蟒蛇/熊猫 - Creating a new column in dataframe based on multiple conditions from other rows and columns? Including rows that are null? - Python/Pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM