首页 > 解决方案 > expand rows based using a series input- pandas

问题描述

i am looking to add a new column and multiply the number of lines in my df for a given series (ex..1,2,3,4) for a given input that looks like below

[{"Name":"bruce","kills":0,"saves":60,"health":10,"energy":10},
{"Name":"clark","kills":25,"saves":100,"health":1000,"energy":10},
{"Name":"diana","kills":15,"saves":80,"health":100,"energy":10}]

Name    kills   saves   health  energy
bruce   0       60      10      10
clark   25      100     1000    10
diana   15      80      100     10

output should be below

Name    kills   saves   health  energy  Quater
bruce   0       60      10      10      1
bruce   0       60      10      10      2
bruce   0       60      10      10      3
bruce   0       60      10      10      4
clark   25      100     1000    10      1
clark   25      100     1000    10      2
clark   25      100     1000    10      3
clark   25      100     1000    10      4
diana   15      80      100     10      1
diana   15      80      100     10      2
diana   15      80      100     10      3
diana   15      80      100     10      4

is there any ways to achieve this in pandas

标签: pythonpandasdataframe

解决方案


Use, DataFrame.assign to create a new column Quater and assign this column a value from the sequence 1, 2, 3.., then use pd.concat to concat the list of dataframes, then use DataFrame.sort_values along with ignore_index=True to sort the dataframe:

df1 = pd.concat([df.assign(Quater=i) for i in range(1, 5)])
df1 = df1.sort_values(by=df1.columns.tolist(), ignore_index=True)

Result:

# print(df1)
     Name  kills  saves  health  energy  Quater
0   bruce      0     60      10      10       1
1   bruce      0     60      10      10       2
2   bruce      0     60      10      10       3
3   bruce      0     60      10      10       4
4   clark     25    100    1000      10       1
5   clark     25    100    1000      10       2
6   clark     25    100    1000      10       3
7   clark     25    100    1000      10       4
8   diana     15     80     100      10       1
9   diana     15     80     100      10       2
10  diana     15     80     100      10       3
11  diana     15     80     100      10       4

推荐阅读