gpt4 book ai didi

python - Pandas:在连接过程后将数据框列名称添加到行

转载 作者:行者123 更新时间:2023-12-05 01:03:41 24 4
gpt4 key购买 nike

我有以下数据框:

df1 = pd.DataFrame({'ID'    : ['T1002.', 'T5006.', 'T5007.'],
'Parent': ['Stay home.', "Stay home.","Stay home."],
'Child' : ['2Severe weather.', "5847.", "Severe weather."]})



ID Parent Child
0 T1002. Stay home. 2Severe weather.
1 T5006. Stay home. 5847.
2 T5007. Stay home. Severe weather.

我想将两列合二为一,并将列名添加到行中。我还希望列的名称以粗体显示。

预期结果:(我无法将列名称 ID 等设为粗体)

             Joined_columns()
0 ID: T1002. Parent: Stay home. Child: 2Severe weather.
1 ID: T5006. Parent: Stay home. Child: 5847.
2 ID: T5007. Parent: Stay home. Child: Severe weather.

连接是通过以下代码完成的:

df1_final=df1.stack().groupby(level=0).apply(' '.join).to_frame(0)

但我不知道如何走到最后。有什么想法吗?

最佳答案

I want to add the two columns into one and also add the columns' name into the rows. I want also the columns names to be in bold.

i would like to have the bold text on Excel.

将格式应用于 Excel 工作表中单元格内的 子字符串 需要编写 rich string

有必要构造一个丰富的字符串列表,然后将它们迭代地写到工作表中。这种方法的困难在于您必须跟踪相对于数据帧其余部分的索引偏移量。

import pandas as pd
import xlsxwriter

# create a workbook / worksheet and format
book = xlsxwriter.Workbook('text.xlsx')
sheet = book.add_worksheet('joined-columns')
bold = book.add_format({'bold': True})

# generate the formatted rich string
df1 = pd.DataFrame({'ID': ['T1002.', 'T5006.', 'T5007.'],
'Parent': ['Stay home.', "Stay home.","Stay home."],
'Child': ['2Severe weather.', "5847.", "Severe weather."]})
# the list of string fragments is generated using
# a double list comprehension.
# this flattens the list of lists, where
# each inner list is [bold, 'key: ', 'value', ' '].
# the trailing space is removed through `[:-1]`
data = df1.apply(
lambda row: [a
for k, v in row.to_dict().items()
for a in [bold, f'{k}: ', v, ' ']
][:-1],
axis=1
).to_list()


# write the title & rich strings
# the list of string fragments has to be unpacked with `*`
# because `write_rich_string` accepts variable
# number or arguments after the cell is specified.
sheet.write(0, 0, 'Joined_columns()')
for idx, cell in enumerate(data):
sheet.write_rich_string(idx + 1, 0, *cell)

book.close()

how it looks in the spreadsheet

关于python - Pandas:在连接过程后将数据框列名称添加到行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73838387/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com