简体   繁体   English

将 Pandas DataFrame 转换为没有 for 循环的一行

[英]Convert Pandas DataFrame to one row without for loops

I got a pandas dataframe like this:我有一个 pandas dataframe 像这样:

    x   y   z
0   a   d   g
1   b   e   h
2   c   f   i

Now I want to convert it into a dataframe with a single row with each cell and row + column as column names:现在我想将其转换为 dataframe 单行,每个单元格和行 + 列作为列名:

    z_2 z_1 z_0 y_2 y_1 y_0 x_2 x_1 x_0
0   i   h   g   f   e   d   c   b   a

I know I can do it like this, but I need to runtime optimize the code, if possible without loops, etc.我知道我可以这样做,但我需要运行时优化代码,如果可能的话没有循环等。

df = pd.DataFrame({"x": ["a", "b", "c"],
                    "y": ["d", "e", "f"],
                    "z": ["g", "h", "i"]})
df.to_dict()
wantedRes = pd.DataFrame()
for key, value in df.items():
    for key2, value2 in value.items():
        wantedRes.insert(loc = 0, column = str(key) + "_" + str(key2),value = [value2] ) 

You can use .stack() for this:您可以为此使用.stack()

s = df.stack()
df_new = pd.DataFrame([s.values],  columns=[f'{j}_{i}' for i, j in s.index])

Output: Output:

  x_0 y_0 z_0 x_1 y_1 z_1 x_2 y_2 z_2
0   a   d   g   b   e   h   c   f   i

You can unstack , rework the index and convert to_frame :您可以unstack ,返工索引和转换to_frame

s = df.unstack()
wantedRes = s.set_axis(s.index.map(lambda x: f'{x[0]}_{x[1]}'))[::-1].to_frame().T

output: output:

  z_2 z_1 z_0 y_2 y_1 y_0 x_2 x_1 x_0
0   i   h   g   f   e   d   c   b   a

暂无
暂无

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

相关问题 将具有多行的Pandas数据框转换为一行 - Convert a Pandas dataframe with multiple rows into one row 将熊猫数据框的一行转换为多行 - Convert one row of a pandas dataframe into multiple rows 将每 2 行中分布的数据转换为 pandas dataframe 中的仅一行 - convert data spread in each 2 row to only one row in pandas dataframe 使用pandas将具有多行的数据帧转换为一行? - Convert a dataframe with multiple rows into one row using pandas? 使用python pandas将具有多行的python数据帧转换为一行? - Convert a python dataframe with multiple rows into one row using python pandas? 为什么 Pandas 将 DataFrame 的一行(或一列)转换为系列? - Why Does Pandas Convert One Row (or Column) of a DataFrame to a Series? Pandas: 重复 Append 一行到不同的 Dataframe (without.append()) - Pandas: Repeatedly Append One Row to Different Dataframe (without .append()) 将 pandas dataframe 中的每一行转换为 dataframe,其中一列在每一行中包含先前在单独列中的值数组 - Convert each row in pandas dataframe to a dataframe with one column containing in each row an array of values previously in seperate columns 在 Pandas 中聚合到当前行而没有循环 - Aggregate up to current row without loops in Pandas Python Pandas 将一列的月/年 dataframe 转换为 dataframe,其中每行为一年 - Python Pandas convert month/year dataframe with one column to dataframe where each row is one year
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM