python - 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
解决方案
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
推荐阅读
- ios - WKWebView 整页截图
- php - Laravel Nova 如何使用基于其他 Nova Resouce 的选项创建选择
- sql - 我可以在 SQL 中“链接”两组数据并检索两者的值以进行比较吗?
- java - 执行 selenium 测试时浏览器未在 Jenkins 中打开
- types - 使用 Prolog 进行类型检查
- android - 为什么 Kotlin 数组不返回计数
- vue.js - 数据太大,无法在移动版图表上显示
- azure-iot-hub - 配置 MAX_OPERATION_TIMEOUT
- entity-framework-core - 如何使用 Entity Framework Core 2.2 播种自引用树
- c++ - 如何将公共方法中的数据添加到同一类中的私有成员数组中?