【问题标题】:How to assign new items to selected column in an existing Pandas csv file如何将新项目分配给现有 Pandas csv 文件中的选定列
【发布时间】:2022-12-06 08:22:37
【问题描述】:

我有个问题。结果,我得到了最后一项。请帮忙。

df = pd.read_csv('patient_data_set_copy_test1.csv')
for index, row in df.iterrows():
    if row['sex'] == 'Men':
        # df1 = pd.DataFrame(colors)
        row['height_p'] : random.randint(149, 192)
        row.to_csv('patient_data_set_copy_test1.csv', header=False)

这是起始文件 CSV:

id,sex,age,weight_p,height_p,BMI,Smoke,Smoke_Years,Smoke_amount_day,Chol_All,LDL,HDL,Sugar1,Sugar2,Sugar3,Systolic_pressure,Diastolic_presurre,Likelihood_of_obesity,Likelihood_of_diabetes,Likelihood_of_coronary_heart_disease
0,Woman,45,,,,Nie,,,,,,,,,,,,,
1,Man,41,,,,Nie,,,,,,,,,,,,,
2,Woman,26,,,,Tak,,,,,,,,,,,,,
3,Men,72,,,,Nie,,,,,,,,,,,,,
4,Woman,69,,,,Tak,,,,,,,,,,,,,
.
.
.
11342, Man,41,,,,Nie,,,,,,,,,,,,,


这是结果:

id,11357
sex,Men
age,82.0
weight_p,
height_p,173
BMI,
Smoke,Tak
Smoke_Years,
Smoke_amount_day,
Chol_All,
LDL,
HDL,
Sugar1,
Sugar2,
Sugar3,
Systolic_pressure,
Diastolic_presurre,
Likelihood_of_obesity,
Likelihood_of_diabetes,
Likelihood_of_coronary_heart_disease,

我想获取所选人员的确切索引,然后更新 CSV 文件。 感谢所有的答复。

【问题讨论】:

  • 你能举一个可重现的例子吗(不是你尝试过的结果) 和精确匹配的输出 ?
  • Result 你提出的问题是你要找的东西?或者您需要一个具有相同形状和更新值的数据框,您将保存到初始 . csv

标签: python pandas csv


【解决方案1】:

看起来您想为 DataFrame 中性别为“Men”的所有行更新 height_p 列,并使用 149 到 192 之间的随机整数。为此,您需要按如下方式修改代码:

import random

df = pd.read_csv('patient_data_set_copy_test1.csv')

# Iterate over the rows of the DataFrame
for index, row in df.iterrows():
    if row['sex'] == 'Men':
        # Update the height_p column with a random integer between 149 and 192
        df.loc[index, 'height_p'] = random.randint(149, 192)

# Save the updated DataFrame to the CSV file
df.to_csv('patient_data_set_copy_test1.csv', header=True)

【讨论】:

    【解决方案2】:

    IIUC,这里不用循环,可以用numpy.where

    import pandas as pd
    import numpy as np
    
    df = pd.read_csv('patient_data_set_copy_test1.csv')
    
    df['height_p'] = np.where(df['sex'].eq('Men'), np.random.randint(149, 192), np.NaN) 
    
    df.to_csv('patient_data_set_copy_test1.csv', index=False)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-15
      • 2015-05-31
      • 1970-01-01
      • 2019-12-20
      • 2014-10-16
      • 2020-10-08
      • 2021-04-09
      • 1970-01-01
      相关资源
      最近更新 更多