gpt4 book ai didi

python - 使用 pandas groupby 时 csv 中的列出现问题

转载 作者:行者123 更新时间:2023-12-01 09:24:39 26 4
gpt4 key购买 nike

我的 csv 中有以下这些列。通常所有这些列都具有如下所示的值,并且代码可以顺利运行。

dec list_namme  list    device        Service    Gate
12 food cookie 200.56.57.58 Shop 123

现在我遇到了问题,我得到了一个包含所有这些列的 csv 文件,但没有它们的内容。这里看起来像..

dec list_namme  list    device  Service Gate

一旦代码运行完毕,它就会创建新的 csv,其中包含意外的以下列。我得到的新列名称为 index ,而且,我得到了错误的 2 列,而不是 3(device service Gate) 列。

index   Gate

对于包含内容的 csv,我没有遇到任何问题,甚至列也正确。

下面是代码。代码是:

if os.path.isfile(client_csv_file):
df=pd.read_csv(csv_file) #Read CSV
df['Gate']=df.Gate.astype(str)
df = df.groupby(['device', 'Service'])['Gate'].apply(lambda x: ', '.join(set(x))).reset_index()
df.to_csv(client_out_file, index=False)

请帮助我在这段代码中解决这个问题。

最佳答案

在空数据帧上执行 groupby 会产生没有 groupby-key 列的数据帧。

一种解决方案是在执行操作之前测试数据帧是否为空:

if os.path.isfile(client_csv_file):
df = pd.read_csv(csv_file)
if df.empty:
df = df[['device', 'Service', 'Gate']]
else:
df['Gate'] = df.Gate.astype(str)
df = df.groupby(['device', 'Service'])['Gate']\
.apply(lambda x: ', '.join(set(x))).reset_index()
df.to_csv(client_out_file, index=False)

关于python - 使用 pandas groupby 时 csv 中的列出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50532497/

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