[英]Is there a way I can add rows of values to a dataframe in new columns, based on existing values in the dataframe?
[英]How to add new rows in existing dataframe based on the column values?
我有一个数据框,但我想根据现有数据框添加新行。 每个 ID 都有自己的组,在该组中它从其父级继承。 但我想将新行附加到数据框中,它会将父 ID 放入新 ID 并添加一个基于其子项的组
例如:
ID | Parent | Group
1001 | 2345 | 1
2001 | 3456 | 1
2002 | 3456 | 1
2003 | 3456 | 1
3001 | 4567 | 2
3002 | 4567 | 2
4012 | 5678 | 3
5123 | 6789 | 3
预期结果:
ID | Parent | Group
1001 | 2345 | 1
2001 | 3456 | 1
2002 | 3456 | 1
2003 | 3456 | 1
3001 | 4567 | 2
3002 | 4567 | 2
4012 | 5678 | 3
5123 | 6789 | 3
2345 | 2345 | 1
3456 | 3456 | 1
4567 | 4567 | 2
5678 | 5678 | 3
6789 | 6789 | 3
我相信你需要concat
与DataFrame.assign
用于覆盖列ID
由Parent
和DataFrame.drop_duplicates
在列表中指定的列删除重复:
df1 = df.assign(ID = df['Parent']).drop_duplicates(['Parent','Group'])
df2 = pd.concat([df, df1], ignore_index=True)
print (df2)
ID Parent Group
0 1001 2345 1
1 2001 3456 1
2 2002 3456 1
3 2003 3456 1
4 3001 4567 2
5 3002 4567 2
6 4012 5678 3
7 5123 6789 3
8 2345 2345 1
9 3456 3456 1
10 4567 4567 2
11 5678 5678 3
12 6789 6789 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.