[英]How can i append pandas dataframe rows under another df rows
I have 2 pandas dataframe, one df has the id column and another df has values i want to add df1.我有 2 pandas dataframe,一个 df 有 id 列,另一个 df 有我想添加 df1 的值。
df1: df1:
id ![]() |
Column A ![]() |
Column B ![]() |
---|---|---|
1 ![]() |
red![]() |
rose![]() |
2 ![]() |
blue![]() |
rose![]() |
3 ![]() |
yellow![]() |
rose![]() |
df2 df2
id ![]() |
Column A ![]() |
Column B ![]() |
---|---|---|
null ![]() |
green![]() |
car![]() |
null ![]() |
grey![]() |
car![]() |
i want to append df2 values to df1 but i need to append data for all id numbers.我想将 append df2 值转换为 df1,但我需要 append 数据来获取所有 ID 号。
output i am trying to get: output 我正在尝试获取:
id ![]() |
Column A ![]() |
Column B ![]() |
---|---|---|
1 ![]() |
red![]() |
rose![]() |
1 ![]() |
green![]() |
car![]() |
1 ![]() |
grey![]() |
car![]() |
2 ![]() |
blue![]() |
rose![]() |
2 ![]() |
green![]() |
car![]() |
2 ![]() |
grey![]() |
car![]() |
3 ![]() |
yellow![]() |
rose![]() |
3 ![]() |
green![]() |
car![]() |
3 ![]() |
grey![]() |
car![]() |
i tried with the for and if else statements but im stuck it我尝试使用 for 和 if else 语句,但我卡住了
You can try cross appling ids from the first dataframe with second one and the concatenating the results:您可以尝试将第一个 dataframe 中的 ID 与第二个交叉应用 ID,然后将结果连接起来:
data = [[1,'red', 'rose'], [2,'blue', 'rose'], [3,'yellow', 'rose']]
df = pd.DataFrame(data, columns=["id", "Column A", "Column B"])
data1 = [['green', 'car' ],['grey','car']]
df1 = pd.DataFrame(data1, columns=["Column A", "Column B"])
pd.concat([df, df[['id']].merge(df1, how='cross')])
Note that this will contain duplicates if some id from df1
will already have data as one of the rows in df2
.请注意,如果来自
df1
的某些 id 已经将数据作为df2
中的行之一,则这将包含重复项。
Output: Output:
id ![]() |
Column A ![]() |
Column B ![]() |
---|---|---|
1 ![]() |
red![]() |
rose![]() |
2 ![]() |
blue![]() |
rose![]() |
3 ![]() |
yellow![]() |
rose![]() |
1 ![]() |
green![]() |
car![]() |
1 ![]() |
grey![]() |
car![]() |
2 ![]() |
green![]() |
car![]() |
2 ![]() |
grey![]() |
car![]() |
3 ![]() |
green![]() |
car![]() |
3 ![]() |
grey![]() |
car![]() |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.