白猪掌柜的
这不是最有效的方法,但它非常可读且易于遵循:import pandas as pddf = pd.DataFrame({'col_a' : [1,2,3], 'col_b':[2,3,4]})index_list_a = [0,2]value_list_a = ['a', 'c']index_list_b = [1]value_list_b = ['b']for index, value in zip( index_list_a + index_list_b, value_list_a + value_list_b): df.loc[index, 'col_f'] = value print(df) col_a col_b col_f0 1 2 a1 2 3 b2 3 4 c其单行且更高效的版本是(正如 @Shubham Sharma 所指出的):df.loc[index_list_a + index_list_b, 'col_f'] = value_list_a + value_list_b
holdtom
首先,您必须更改分配部分以使用 loc 并为 col_f 添加占位符df['col_f'] = np.nandf.loc[df.index.isin(index_list_a),"col_f"] = value_list_a其次我认为你有错误。你的代码有索引[1,3],但python从0开始。index_list_a = [0,2]value_list_a = ['a', 'c']import pandas as pdimport numpy as npdf = pd.DataFrame({'col_a' : [1,2,3], 'col_b':[2,3,4]})index_list_a = [0,2]value_list_a = ['a', 'c']index_list_b = [2]value_list_b = ['b']df['col_f'] = np.nandf.loc[df.index.isin(index_list_a),"col_f"] = value_list_a但是如果你想要一个通用的解决方案并且 [1,3] 是故意的,你可以使用下面的函数def create_intersect(x,y,z): common = list(set(x).intersection(set(y))) for i in range(len(y)): if y[i] not in common: y.pop(i); z.pop(i); return y,z这允许您预先消除数据框中不存在的任何索引import pandas as pdimport numpy as npdef create_intersect(x,y,z): common = list(set(x).intersection(set(y))) for i in range(len(y)): if y[i] not in common: y.pop(i); z.pop(i); return y,zdf = pd.DataFrame({'col_a' : [1,2,3], 'col_b':[2,3,4]})index_list_a,value_list_a = create_intersect(df.index, [1,3], ['a', 'c'])df['col_f'] = np.nandf.loc[df.index.isin(index_list_a),"col_f"] = value_list_a