gpt4 book ai didi

python - Excel 电子表格的 Pandas groupby

转载 作者:行者123 更新时间:2023-12-01 08:10:47 25 4
gpt4 key购买 nike

我有一个如下所示的电子表格(大约 1800 行),它是通过从 Access 数据库中提取信息的 python 脚本生成的:

ID  Chemical            Association  Term 
1 1,1-Dichloroethene exactMatch 1,1-Dichloroethylene
1 1,1-Dichloroethene exactMatch Vinylidene Chloride
2 1,2 Epoxyethane exactMatch Ethylene oxide
2 1,2 Epoxyethane exactMatch Ethylene oxide (1,2 Epoxyethane)

我想使用 pandas 来更改此电子表格的布局。我想创建一个像这样的表:

ID  Chemical            Association  Term                   (new column)
1 1,1-Dichloroethene exactMatch 1,1-Dichloroethylene Vinylidene Chloride
2 1,2 Epoxyethane exactMatch Ethylene oxide (1... Ethylene oxide

到目前为止,我已经使用 pandas 编写了以下内容,但不确定下一步该怎么做:

data = pd.read_excel('Chemicals_exactMatch.xlsx', sheet_name='Sheet1')
df = pd.DataFrame(data)
grp = df.groupby(['ID','Chemical','Association'])

我认为需要将以下语句纳入其中,但我不确定如何:

df.apply(lambda grouped: grouped['Term'].str.cat(sep="|"))
df.str.split(pat="|")

最佳答案

我已经成功编写了以下有效的代码:

data = pd.read_excel(spreadsheet, sheet_name='Sheet1')
df = (pd.DataFrame(data)
.groupby(['ID','Chemical','Association'])
.apply(lambda grouped: grouped['Term'].str.cat(sep="!"))
.str.split(pat="!", expand=True)
.sort_values('Chemical')
.to_excel('Chemicals_exactMatch.xlsx'))

关于python - Excel 电子表格的 Pandas groupby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55265754/

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