[英]How to shift and stack two columns of pandas Dataframe into one column?
[英]How to stack two columns of a pandas dataframe in python
我想將兩列堆疊在一起
所以我在一列中各有左值和右值,並想將它們組合成一個。 我如何在 Python 中執行此操作? 我正在使用 Pandas 數據幀。
基本上從這個
Left Right
0 20 25
1 15 18
2 10 35
3 0 5
對此:
New Name
0 20
1 15
2 10
3 0
4 25
5 18
6 35
7 5
它們的組合方式無關緊要,因為我會 plot 無論如何,新的列名也無關緊要,因為我可以重命名它。
您可以創建一個 cols 列表,並調用 squeeze 來匿名化數據,這樣它就不會嘗試在列上對齊,然后在此列表上調用 concat,傳遞 ignore_index=True 創建一個新索引,否則您將獲得名稱作為索引值重復:
cols = [df[col].squeeze() for col in df]
pd.concat(cols, ignore_index=True)
許多選項, stack
, melt
, concat
,...
這是一個:
>>> df.melt(value_name='New Name').drop('variable', 1)
New Name
0 20
1 15
2 10
3 0
4 25
5 18
6 35
7 5
您還可以使用np.ravel
:
import numpy as np
out = pd.DataFrame(np.ravel(df.values.T), columns=['New name'])
print(out)
# Output
New name
0 20
1 15
2 10
3 0
4 25
5 18
6 35
7 5
更新
如果你只有 2 列:
out = pd.concat([df['Left'], df['Right']], ignore_index=True).to_frame('New name')
print(out)
# Output
New name
0 20
1 15
2 10
3 0
4 25
5 18
6 35
7 5
unstack
的解決方案
df2 = df.unstack()
# recreate index
df2.index = np.arange(len(df2))
帶masking
的解決方案。
# Your data
import numpy as np
import pandas as pd
df = pd.DataFrame({"Left":[20,15,10,0], "Right":[25,18,35,5]})
# Masking columns to ravel
df2 = pd.DataFrame({"New Name":np.ravel(df[["Left","Right"]])})
df2
New Name
0 20
1 25
2 15
3 18
4 10
5 35
6 0
7 5
我最終使用了這個解決方案,似乎工作正常
df1 = dfTest[['Left']].copy()
df2 = dfTest[['Right']].copy()
df2.columns=['Left']
df3 = pd.concat([df1, df2],ignore_index=True)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.