【发布时间】:2019-06-14 00:22:53
【问题描述】:
这个问题其实大概2个案例:
- 将 pandas 数据框列中的相同值设为空白
- 将结果数据框保存到合并单元格的 Excel 中,文本位于垂直中心
1.数据框部分
对于数据框
df = pd.DataFrame({'Company': ['Huawei','Huawei','Huawei', 'Apple', 'Apple', 'Samsung', 'Samsung'],
'Year': [2011, 2011, 2018, 2011, 2019, 2018, 2019],
'Product': ['H1', 'H2', 'H3', 'A1', 'A2', 'S1', 'S2']})
df = df.sort_values(by=['Company', 'Year'])
df
即
公司年份 产品 3 苹果 2011 A1 4 苹果 2019 A2 0 华为 2011 H1 1 华为 2011 H2 2 华为 2018 H3 5 三星 2018 S1 6 三星 2019 S2我需要的是mergeCell(df, on = ['Company'])返回
mergeCell(df, on = ['Company', 'Year']) 返回时
我写了一个,但显然它不简洁并且有错误
def mergeCell(df, on):
import copy
dfMerged = df[on]
dfTmp = np.empty((df.shape[0], len(on)), dtype=object)
lastRow = ()
idx = 0
for row in dfMerged.itertuples():
if idx == 0:
lastRow = row[1:]
dfTmp[idx, :] = lastRow
else:
if row[1:] != lastRow:
lastRow = row[1:]
dfTmp[idx, :] = lastRow
else:
dfTmp[idx, :] = np.empty((1, len(on)), dtype=object)
idx += 1
dfTmp = pd.DataFrame(dfTmp)
dfTmp.columns = on
dfCopied = copy.deepcopy(df)
for idxRow in range(df.shape[0]):
for idxCol in on:
dfCopied.loc[idxRow, idxCol] = dfTmp.loc[idxRow, idxCol]
return dfCopied
那么,有没有内置的方法可以做到这一点?
2。将结果数据框保存到合并单元格的 excel 中,文本位于垂直中心
对于这部分,除了做我在上面的mergeCell函数中所做的事情之外,我不知道
谢谢
【问题讨论】:
-
我建议您单独提出第二个问题,展示您研究过的内容。我只在回答中解决了第一个问题。
标签: python excel pandas dataframe merge