Python pandas 點樣先grouping 再transpose

有個Excel table 1, 如果用python pandas 點樣可以變成table 2?

Excel table 1
A 1
A 2
B 3
B 4
B 5
C 6

Excel table 2
A 1 2
B 3 4 5
C 6

您可以使用pandas的`groupby`和`agg`函數將Table 1轉換為Table 2。以下是一個示例代碼:

python
import pandas as pd

# 假設您已經將Excel表格讀入一個名為df的pandas DataFrame

# 創建一個函數來將分組後的值轉換為列表
def join_values(series):
    return series.tolist()

# 將DataFrame按照第一列進行分組,並將分組後的值轉換為列表
table_2 = df.groupby(df.columns[0], as_index=False).agg(join_values)

# 將結果DataFrame轉換為Excel表格
table_2.to_excel("table_2.xlsx", index=False)

這將把Table 1轉換為Table 2,並將結果保存為名為`table_2.xlsx`的Excel文件。請注意,您需要根據您的需求修改代碼中的表格名稱和文件名。

TOP

  1. import pandas as pd

  2. # Assuming your data is in a list of tuples
  3. data = [('A', 1), ('A', 2), ('B', 3), ('B', 4), ('B', 5), ('C', 6)]

  4. # Convert the data to a DataFrame
  5. df = pd.DataFrame(data, columns=['Letter', 'Number'])

  6. # Group by 'Letter' and transform the 'Number' column to a list
  7. df_grouped = df.groupby('Letter')['Number'].apply(list)

  8. # Convert the grouped data back to a DataFrame and reset the index
  9. df_transposed = pd.DataFrame(df_grouped).reset_index()

  10. print(df_transposed)

  11. # Create a new DataFrame where each number is a separate column
  12. df_final = pd.DataFrame(df_transposed['Number'].to_list(), index=df_transposed.Letter)

  13. print(df_final)

  14. df_final = df_final.fillna(0)
複製代碼

TOP

本帖最後由 EITCo 於 2023-11-30 17:44 編輯

另一個唔用轉做list嘅方法
  1. import pandas as pd
  2. df = pd.read_excel(r'D:\input.xlsx', header=None)
  3. print(df)
  4. '''
  5.    0  1
  6. 0  A  1
  7. 1  A  2
  8. 2  B  3
  9. 3  B  4
  10. 4  B  5
  11. 5  C  6
  12. '''

  13. df['col'] = df.groupby(0).cumcount()
  14. print(df)
  15. '''
  16.    0  1  col
  17. 0  A  1    0
  18. 1  A  2    1
  19. 2  B  3    0
  20. 3  B  4    1
  21. 4  B  5    2
  22. 5  C  6    0
  23. '''

  24. out = df.pivot(columns='col', index=0)[1]
  25. print(out)
  26. '''
  27. col    0    1    2
  28. 0                 
  29. A    1.0  2.0  NaN
  30. B    3.0  4.0  5.0
  31. C    6.0  NaN  NaN
  32. '''

  33. out.to_excel(r'D:\output.xlsx', header=False)
複製代碼
附件: 您需要登錄才可以下載或查看附件。沒有帳號?註冊

TOP

回覆 4# EITCo


    呢個方法,即抄即用,完全做到我要既野

TOP