![](/img/trans.png)
[英]Append new Pandas DataFrame to an old one without column names sorted
[英]Pandas make a new dataframe with the old column names
我需要一些幫助來構造數據。 所以我有以下DataFrame(稱為df):
我想基於Mean_CArea,Mean_CPressure和Mean_Force對數據框進行分組。 但是,我得到了以下結果:
您可能會看到列名稱是0,1,2,而不是NATIVE_RH,ANATOMICAL_RH和NON_ANATOMICAL_RH。 有沒有辦法從原始數據框中獲取正確的列名?
到目前為止,這是我的代碼:
def function(self, df):
d = dict()
for head in df.columns.tolist():
RH, j_mechanics = head
if j_mechanics not in d:
d[j_mechanics] = df[head]
else:
d[j_mechanics] = pd.concat([d[j_mechanics],df[head]], axis=1, ignore_index=True)
for df_name, df in sorted(d.items()):
print(df_name)
print(df.head())
預先感謝!
IIUC您可以將swaplevel
與groupby
按列( axis=1
)和按第一級( level=0
)一起使用:
df = pd.DataFrame({('B', 'a'): {0: 4, 1: 10}, ('B', 'b'): {0: 5, 1: 11}, ('B', 'c'): {0: 6, 1: 12}, ('A', 'a'): {0: 1, 1: 7}, ('A', 'c'): {0: 3, 1: 9}, ('A', 'b'): {0: 2, 1: 8}})
print (df)
A B
a b c a b c
0 1 2 3 4 5 6
1 7 8 9 10 11 12
df.columns = df.columns.swaplevel(0,1)
for i, g in df.groupby(level=0, axis=1):
print (g)
a
A B
0 1 4
1 7 10
b
A B
0 2 5
1 8 11
c
A B
0 3 6
1 9 12
您想使用xs
df.xs('Mean_CArea', axis=1, level=1)
和
df.xs('Mean_CPressure', axis=1, level=1)
和
df.xs('Mean_Force', axis=1, level=1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.