简体   繁体   English

我怎么能在另一个 df 行下 append pandas dataframe 行

[英]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 ID Column A A列 Column B B列
1 1个 red红色的 rose玫瑰
2 2个 blue蓝色的 rose玫瑰
3 3个 yellow黄色 rose玫瑰

df2 df2

id ID Column A A列 Column B B列
null null green绿色 car
null 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 ID Column A A列 Column B B列
1 1个 red红色的 rose玫瑰
1 1个 green绿色 car
1 1个 grey灰色的 car
2 2个 blue蓝色的 rose玫瑰
2 2个 green绿色 car
2 2个 grey灰色的 car
3 3个 yellow黄色 rose玫瑰
3 3个 green绿色 car
3 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 ID Column A A列 Column B B列
1 1个 red红色的 rose玫瑰
2 2个 blue蓝色的 rose玫瑰
3 3个 yellow黄色 rose玫瑰
1 1个 green绿色 car
1 1个 grey灰色的 car
2 2个 green绿色 car
2 2个 grey灰色的 car
3 3个 green绿色 car
3 3个 grey灰色的 car

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

相关问题 df.append()不向熊猫中的数据框添加行 - df.append() not adding rows to dataframe in pandas 如何重新排列和 append 包含在一个 df 的列中的数据在另一个 dataframe 的行中 - How to rearrange and append data contained in a column of a df in the rows of another dataframe 对于第一个 df 中值的所有实例,如何用另一个 dataframe 的值替换 pandas 行? - How do I replace pandas rows with values of another dataframe for all instances of the value in the first df? 我怎样才能在 pandas 中只显示与另一个 dataframe 共同的行? - How can I only show rows common with another dataframe in pandas? Pandas:将数据帧附加到另一个 df - Pandas: append dataframe to another df 如何将 dataframe 与另一个 df 进行比较,并使用 pandas 从第一个 df 返回新行 - How to compare a dataframe with another df and return new rows from the first df using pandas 如何将重复的行添加到 Pandas DF? - how can I add duplicated rows to a Pandas DF? 如何复制 Pandas DataFrame 的行? - How can I replicate rows of a Pandas DataFrame? 创建循环以从数据框中动态选择行,然后将选定的行追加到另一个数据框:df.query() - Create Loop to dynamically select rows from dataframe, then append selected rows to another dataframe: df.query() 如何在 for 循环中追加 pandas.DataFrame 中的行 - How to append rows in pandas.DataFrame in for loop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM