[英]Pandas values transfer from one df to another OverflowError
Is there pandas way to copy values to column 'column_to_fill' from another df without itterations?是否有 pandas 方法可以将值从另一个 df 复制到列“column_to_fill”而无需迭代? I have needed me row and column indexes in df_1 columns.我需要 df_1 列中的行和列索引。 I need to fill df_1['column_to_fill'] with values from df_2.我需要用 df_2 中的值填充 df_1['column_to_fill']。
df1 = pd.DataFrame(columns=['row_df2', 'column_df2'])
df1['row_df2'] = [1, 3, 5]
df1['column_df2'] = ['a', 'c', 'd']
index=np.arange(6)
columns=['a', 'b', 'c', 'd']
df2 = pd.DataFrame(data=np.random.randint(10, size=(len(index), len(columns))), index=index, columns=columns)
df1['column_to_fill'] = 0
for idx in df1.index:
df1.loc[idx, 'column_to_fill'] = df2.loc[df1.loc[idx, 'row_df2'],
df1.loc[idx, 'column_df2']].sum()
df1
row_df2 column_df2
0 1 a
1 3 c
2 5 d
df2
a b c d
0 2 3 5 2
1 8 3 9 3
2 4 6 0 1
3 3 8 0 8
4 3 4 5 0
5 2 5 4 0
df1
row_df2 column_df2 column_to_fill
0 1 a 8
1 3 c 0
2 5 d 0
If I understand you well, you want to assign a column from a df to another, then:如果我理解你,你想将一个列从一个 df 分配给另一个,然后:
df2['column_to_fill'] = df1['col']
I think you want to pick the value of the df_2 based on the values(row and column combination) of df_1 and assign it to df_1 column.我认为您想根据 df_1 的值(行和列组合)选择 df_2 的值并将其分配给 df_1 列。 If that is the case then check below.,如果是这种情况,请检查以下内容。
df_1 = pd.DataFrame({'values_type_rows_df2':[0,1,0,1], 1:[4,5,6,7]})
df_2 = pd.DataFrame({0:['a','b','c','d'], 1:['e','a','b','c']})
df_1['column_to_fill'] = [df_2.loc[i,i] for i in df_1['values_type_rows_df2']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.