【问题标题】:Append new row with existing iterate row in CSV file python在 CSV 文件 python 中使用现有的迭代行追加新行
【发布时间】:2023-03-31 00:48:01
【问题描述】:

我有 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 新手,我有点陷入困境,请帮助我谢谢!

【问题讨论】:

  • Highly_low 来自哪里?如果你想写入 csv。使用 pd.DataFrame.to_csv() 函数!
  • 对不起,我修改了我的代码。
  • 怎么样使用..print(uuid.uuid1().hex[:8],"REP"+str(uuid.uuid4().hex[:9]),row['Sales_Region'][['CUS_KEY', 'Unique Key ' , 'Sales_Region']])
  • @banpd,看看上面是否有帮助,但是,您在示例中只显示了两列?那是真的..

标签: python pandas csv export-to-csv


【解决方案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'])

【讨论】:

  • 不会报错TypeError: '&gt;=' not supported between instances of 'str' and 'int' 吗?使用low_sales =df[(df['Dollar_value'] &gt;=500) &amp; (df['Dollar_value']&lt;=1000)]
  • @pygo - 你的Dollar_value 专栏是什么?有数字吗?
  • @jezrael ,是的,我只是在看 op 提供的数据框。
【解决方案2】:

================================================ =================

对于核心 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()

================================================ ========================

在 Pandas 中,以下代码应该可以解决您的问题:-

df = pd.read_csv("myfile.csv")
df['new_column'] = 'some_value'
df.to_csv('myfile.csv')

【讨论】:

    【解决方案3】:

    我想,你需要这个:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-05
      • 1970-01-01
      • 2011-01-22
      • 1970-01-01
      • 1970-01-01
      • 2020-01-23
      相关资源
      最近更新 更多