[英]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.