【问题标题】:How to insert values based on condition in column in the CSV file using Python?如何使用 Python 在 CSV 文件的列中插入基于条件的值?
【发布时间】:2021-12-07 22:17:35
【问题描述】:

我想根据条件从列表中插入值,

例如,请在下面找到我使用CSV模块的代码算法。

out_file = open("c://Project//in.csv", "w")
header = ['List','Integer', 'Float', 'String']
l = [[4,5], 12, 2.4, "This is a string", [1,2], 45, ["Second String"]]
writer = csv.writer(out_file)
insert_header_in_the_beginning
for i in l:
    if check_first_element_is_list_using_regex:
        insert_in_first_column_of_first_row(i)
    elif check_second_element_is_integer_using_regex:
        insert_in_second_column_of_first_row(i)
    elif check_third_element_is_float_using_regex:
        insert_in_third_column_of_first_row(i)
    elif check_last_element_is_string_using_regex:
        insert_in_last_column_of_first_row(i)
    new_row_starts

期望的输出

List    Integer    Float    String
[4,5]    12         2.4     This is a String
[1,2]    45         None    Second String
.....        

【问题讨论】:

  • 我意识到这是伪代码,但我不明白使用 RE 分析列表内容的明显意图。你能解释一下吗?另外,请根据您的示例数据显示您的预期输出(CSV 文件内容)应该是什么样子
  • @BrutusForcus 使用 RE 识别元素是 Char、Int 还是 Decimal。实际上在这里我只是展示了一个最简单的例子,但是实际代码中的列表具有复杂的模式。是的,我已经在我的问题中更新了所需的输出。谢谢!

标签: python python-3.x list python-2.7 csv


【解决方案1】:

循环不是一个好主意。您有两个更好的选择:您可以将 np.select 与两个条件列表一起使用,值如下:

condlist = [x<3, x>5]
choicelist = [x, x**2]
np.select(condlist, choicelist)

为了轻松解决您的问题:

import pandas as pd

liste_of_Liste = []
liste_of_Integer = []
liste_of_Float = []
liste_of_String = []
l = [[4,5], 12, 2.4, "This is a string", [1,2], 45, ["Second String"]]
for i in l:
    if type(i) is list:
        liste_of_Liste.append(i)
    elif type(i) is int:
        liste_of_Integer.append(i)
    elif type(i) is float:
        liste_of_Float.append(i)
    else:
        liste_of_String.append(i)

然后你的数组没有相同的长度,我把它放在行中,但如果你愿意,你可以用 NaN 值填充它:

your_dictionnary = {
    'List'    : liste_of_Liste,
    'Integer' : liste_of_Integer,
    'Float'   : liste_of_Float,
    'String'  : liste_of_String
    }

df = pd.DataFrame.from_dict(your_dictionnary, orient="index")
print(df)

【讨论】:

  • 您好,感谢您的回复。您能否根据我在问题中提到的数据提供解决方案?
  • 我用更简单的方式编辑了,如果可以的话告诉我
猜你喜欢
  • 2021-05-08
  • 1970-01-01
  • 1970-01-01
  • 2018-06-10
  • 2018-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-13
相关资源
最近更新 更多