[英]How to convert each row of a dataframe to new column use concat in python
If I have dataframes,如果我有数据框,
df1 = pd.DataFrame(
{
"A": ["A0", "A1", "A2", "A3"],
"B": ["B0", "B1", "B2", "B3"],
"C": ["C0", "C1", "C2", "C3"],
"D": ["D0", "D1", "D2", "D3"],
},
index=[0, 1, 2, 3],)
df2 = pd.DataFrame(
{
"A": ["A4", "A5", "A6", "A7"],
"B": ["B4", "B5", "B6", "B7"],
"C": ["C4", "C5", "C6", "C7"],
"D": ["D4", "D5", "D6", "D7"],
},
index=[4,5,6,7],)
I want to use pd.concat to combine these two dataframes as我想使用 pd.concat 将这两个数据帧组合为
dfnew = pd.concat([df1.loc[0],
df1.loc[1],
df1.loc[2],
df1.loc[3],
df2.loc[4],
df2.loc[5],
df2.loc[6],
df2.loc[7]],
axis=0,sort=False)
dfnew = dfnew.to_frame().transpose()
dfnew is a 1row x 32 columns dataframe. But how about I have many rows in df1 and df2, or I want to combine different number of rows of df1 and df2 in a loop? dfnew 是 1 行 x 32 列 dataframe。但是我在 df1 和 df2 中有很多行,或者我想在一个循环中组合不同行数的 df1 和 df2 怎么样? What can I do for the concat.loc[] part?我可以为 concat.loc[] 部分做什么? Or is there another way to do this?还是有另一种方法可以做到这一点?
Thank you ahead.先谢谢你。
IIUC, you could stack
the individual dataframes, concat
and reshape: concat
,您可以stack
各个数据帧,连接并重塑:
dfnew = pd.concat([df1.stack(), df2.stack()]).droplevel(0).to_frame().T
output: output:
A B C D A B C D A B C D A B C D A B C D A B C D A B C D A B C D
0 A0 B0 C0 D0 A1 B1 C1 D1 A2 B2 C2 D2 A3 B3 C3 D3 A4 B4 C4 D4 A5 B5 C5 D5 A6 B6 C6 D6 A7 B7 C7 D7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.