如何使用Python在CSV文件中根据列的条件插入值?



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

例如,下面是我使用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
.....        

循环不是一个好主意。你有两个更好的选择:你可以用np。使用两个条件列表进行选择,值如下所示:

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)

最新更新