【问题标题】:CSV: alternative to excel "IF" statement in python. Read column and create a new one with numpy.where or other functionCSV:替代python中的excel“IF”语句。阅读列并使用 numpy.where 或其他功能创建一个新列
【发布时间】:2021-07-06 15:17:51
【问题描述】:

我有一个包含多个列的 CSV 文件,我想编写一个代码来读取名为 'ARPU 平均 6 个月 w/t 漫游和折扣' 的特定列,然后创建一个新的名为“Logical”的列将基于 numpy.where()。这是我目前得到的:

csv_data = pd.read_csv("Results.csv")

data = csv_data[['ARPU average 6 month w/t roaming and discount']]
data = data.to_numpy()

sol = []
for target in data:
    if1 = np.where(data < 0, 1, 0)
    sol.append(if1)

csv_data["Logical"] = [sol].values
csv_data.to_csv ('Results2.csv', index = False, header=True)

这个循环不正确并且不起作用。它不会为每一行创建具有相应值的新列。明确一点:如果列中的值大于0,则记录“1”,否则记录“0”。解决方案可以是任何方式(也不需要 np.where(),也不需要循环)

如果您想了解什么是“Results.csv”

它实际上是一个包含数据的大文件,我已经突出显示了我们使用的列。代码需要检查列中是否有大于 0 的值,并在新列中返回 1 或 0(如我在问题中所述)

【问题讨论】:

  • csv_data['Logical'] = np.where(csv_data['ARPU average 6 month w/t roaming and discount'] &gt; 0, 1, 0) 或者只是做csv_data['Logical'] = (csv_data['ARPU average 6 month w/t roaming and discount'] &gt; 0).astype(int)
  • @It_is_Chris 我可以要求展示如何在代码中实现它,因为我已经尝试过这个版本但仍然无法工作?也许我做了一些不正确的事前/事后工作。谢谢!

标签: python numpy csv


【解决方案1】:

更新答案

import pandas as pd 

f1 = pd.read_csv("L1.csv") 
f2 = pd.read_csv("L2.csv") 

f3 = pd.merge(f1, f2, on ='CTN', how ='inner') 

# f3.to_csv("Results.csv") # -> you do not need to save the file to a csv unless you really want to
# csv_data = pd.read_csv("Results.csv") # -> f3 is already saved in memory you do not need to read it again
# data = csv_data[['ARPU average 6 month w/t roaming and discount']] # -> you do not need this line

f3['Logical'] = (f3['ARPU average 6 month w/t roaming and discount']>0).astype(int)
f3.to_csv('Results2.csv', index = False, header=True)

原答案

在使用 pandas 或 numpy 时,通常不需要使用循环。拿这个示例数据框:df = pd.DataFrame([0,1,2,3,0,0,0,1], columns=['data'])

您可以简单地使用返回的布尔值(其中列大于 0 返回 1 否则返回 0)来创建新列。

df['new_col'] = (df['data'] > 0).astype(int)

   data  new_col
0     0        0
1     1        1
2     2        1
3     3        1
4     0        0
5     0        0
6     0        0
7     1        1

或者如果你想要我们 numpy

df['new_col'] = np.where(df['data']>0, 1, 0)

   data  new_col
0     0        0
1     1        1
2     2        1
3     3        1
4     0        0
5     0        0
6     0        0
7     1        1

【讨论】:

  • 所以会是这样?不好意思问,我只是个初学者``` import numpy as np import pandas as pd f1 = pd.read_csv("L1.csv") f2 = pd.read_csv("L2.csv") f3 = pd. merge(f1, f2, on ='CTN', how ='inner') f3.to_csv("Results.csv") csv_data = pd.read_csv("Results.csv") data = csv_data[['ARPU平均6个月w/t 漫游和折扣']] data = data.to_numpy() data['new_col'] = np.where(data['ARPU 平均 6 个月 w/t 漫游和折扣']>0, 1, 0) csv_data .to_csv ('Results2.csv', index = False, header=True) ```
猜你喜欢
  • 2019-06-20
  • 1970-01-01
  • 2021-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-03
相关资源
最近更新 更多