我有CSV文件Sales_In.csv,DataFrame是:
Sales_Region Dollar_value
East 500
west 500
south 500
North 2000
我正在使用熊猫
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的新手,有点被困在这帮助我了!
答案 0 :(得分:1)
使用列表推导创建值的元组,由构造器创建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'])
答案 1 :(得分:0)
尝试一下:
将列分配给df。
df.columns = ['CUS_KEY','Unique Key','Sales_Region']
然后写入csv。
df.to_csv('abc.csv', index=False, header=True)
答案 2 :(得分:0)
================================================ =================
对于核心python,您可以使用csv追加新行。 确保file.csv将位于正确的文件夹中
import csv
row = ['4', 'Anoop', 'Chamba']
with open('file.csv', 'a') as csvFile:
writer = csv.writer(csvFile)
writer.writerow(row)
csvFile.close()
================================================ ======================
在熊猫中,以下代码可以解决您的问题:-
df = pd.read_csv("myfile.csv")
df['new_column'] = 'some_value'
df.to_csv('myfile.csv')
答案 3 :(得分:0)
我认为,您需要这样做:
df_2 = pd.DataFrame()
for loop in low_sales.Sales_Region:
df_2 = df_2.append({'CUS_KEY':uuid.uuid1().hex[:8],
'Unique Key':"REP"+str(uuid.uuid4().hex[:9]),
'Sales_Region':loop},ignore_index=True)
然后:
df_2.to_csv('New_df.csv', index=False, header=True)