gpt4 book ai didi

python - 在 CSV 文件 python 中添加新行和现有迭代行

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

我有 CSV 文件 Sales_In.csv 和 DataFrame 是:

Sales_Region     Dollar_value
East 500
west 500
south 500
North 2000

我正在使用 Pandas

import pandas as pd
import UUID

df= pd.read_csv('Sales_In.csv')
low_sales =df[(df['Dollar_value'] >=500) & (df['Dollar_value']<=1000)]

for index,row in low_sales.iterrows():
for loop in range(10):
print(uuid.uuid1().hex[:8],"REP"+str(uuid.uuid4().hex[:9]),row['Sales_Region'])

上面的代码给了我如下的输出

279418fe HCP6eacac48a East
279418ff HCP6fb7d0ec2 East
27941900 HCP21cb84de3 East
27941901 HCP9b6a34bf0 East
27941902 HCP6aa9f0e20 East
27941903 HCP6fa5e3201 East
27941904 HCPabecf8c42 East
27941905 HCP0922c8acc East
27941906 HCPea9e91d7c East
27941907 HCP95f8dbfb9 East

我想将其写入带有如下标题的 csv 文件

CUS_KEY   Unique Key    Sales_Region
279418fe HCP6eacac48a East
279418ff HCP6fb7d0ec2 East
27941900 HCP21cb84de3 East
...................

我是 python 新手,我有点陷入困境,请帮助我,谢谢!

最佳答案

使用列表理解来创建值元组,由构造函数创建DataFrame,最后由 to_csv 写入文件:

low_sales =df[(df['Dollar_value'] >=500) & (df['Dollar_value']<=1000)]

L = [(uuid.uuid1().hex[:8],"REP"+str(uuid.uuid4().hex[:9]),x)
for x in low_sales['Sales_Region'] for i in range(10)]

df = pd.DataFrame(L, columns=['CUS_KEY','Unique Key','Sales_Region'])
print (df.head(10))
CUS_KEY Unique Key Sales_Region
0 96cdb1f8 REPf2fedbce5 East
1 96cdb1f9 REPfc6d311f4 East
2 96cdb1fa REPa31a28651 East
3 96cdb1fb REP4f4689565 East
4 96cdb1fc REP9e0a484a7 East
5 96cdb1fd REPa8f763796 East
6 96cdb1fe REP442ad19dd East
7 96cdb1ff REPa317fa7b0 East
8 96cdb200 REPb14ca95b9 East
9 96cdb201 REP60c31eb67 East

df.to_csv(file, index=False)

如果想使用您的代码:

L = []
for index,row in low_sales.iterrows():
for loop in range(10):
L.append((uuid.uuid1().hex[:8],"REP"+str(uuid.uuid4().hex[:9]),row['Sales_Region']))

df = pd.DataFrame(L, columns=['CUS_KEY','Unique Key','Sales_Region'])

关于python - 在 CSV 文件 python 中添加新行和现有迭代行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52887390/

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