![](/img/trans.png)
[英]Python: How to Combine (concat) Multiple Excel Files into One File? (Not append)
[英]Concat excel cols and combine rows into one using python pandas
我在 excel 表中有一个数据,如下所示
Name Segment revenue Product_id Status Order_count days_ago
Dummy High value 1000 P_ABC Yes 2 30 days ago
Dummy High value 1000 P_CDE No 1 20 days ago
Dummy High value 1000 P_EFG Yes 3 10 days ago
Tammy Low value 50 P_ABC No 0 100 days ago
Tammy Low_value 50 P_DCF Yes 1 10 days ago
我想按顺序执行以下步骤
a) 将列Product_id, Status, Order_count
合并为一列。 使用-
值之间的符号
b) 根据Name, Segment and revenue
对数据进行分组
c) 将同一组的多行合并为一行(在 Excel 中)。
我试过类似下面的东西
df['concat_value'] = df['Product_id'] + " - " + df['Status'] + " - " + df['Order_count']
df_group = df.groupby(['Name','Segment','revenue'])
df_nonrepeats = df[df_group['concat_value'].transform('count') == 1]
df_repeats = df[df_group['concat_value'].transform('count') > 1]
但是我无法获得如下 excel 表中所示的预期输出。
你能帮我看看如何在 excel 表中获得以下输出吗?
首先通过\n
为新行聚合值,然后为列concat_value
添加text_wrap
格式 - 它通过mapping
映射到 excel 列名称。
如果concat_value
最大26.
,则解决方案有效。列 - 映射到Z
excel 列名称:
import string
df['concat_value'] = df['Product_id'] + " - " + df['Status'] + " - " + df['Order_count'] .astype(str)
df = df.groupby(['Name','Segment','revenue'])['concat_value'].agg('\n'.join).reset_index()
mapping = dict(enumerate(string.ascii_uppercase))
print (mapping)
{0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F', 6: 'G',
7: 'H', 8: 'I', 9: 'J', 10: 'K', 11: 'L', 12: 'M', 13: 'N',
14: 'O', 15: 'P', 16: 'Q', 17: 'R', 18: 'S', 19: 'T',
20: 'U', 21: 'V', 22: 'W', 23: 'X', 24: 'Y', 25: 'Z'}
pos = df.columns.get_loc('concat_value')
print (pos)
3
print (mapping[pos])
D
#https://stackoverflow.com/a/72054821/2901002
with pd.ExcelWriter('file.xlsx', engine='xlsxwriter') as writer:
df.to_excel(writer, sheet_name='Sheet1', index=False)
workbook = writer.book
worksheet = writer.sheets['Sheet1']
cell_format = workbook.add_format({'text_wrap': True})
worksheet.set_column(mapping[pos] + ':' + mapping[pos], cell_format=cell_format)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.