【发布时间】:2018-02-24 16:54:14
【问题描述】:
我想知道是否有最快的代码来替换两个for循环,假设df大小非常大。在我的真实案例中,每个数据框是 200 行和 25 列。
data_df1 = np.array([['Name','Unit','Attribute','Date'],['a','A',1,2014],['b','B',2,2015],['c','C',3,2016],\
['d','D',4,2017],['e','E',5,2018]])
data_df2 = np.array([['Name','Unit','Date'],['a','F',2019],['b','G',2020],['e','H',2021],\
['f','I',2022]])
df1 = pd.DataFrame(data=data_df1)
print('df1:')
print(df1)
df2 = pd.DataFrame(data=data_df2)
print('df2:')
print(df2)
row_df1 = [1,2,5]
col_df1 = [1,3]
row_df2 = [1,2,3]
col_df2 = [1,2]
for i in range(0,len(row_df1)):
for j in range(0, len(col_df1)):
df1.set_value(row_df1[i],col_df1[j], df2.loc[row_df2[i],col_df2[j]])
print('df1 after operation:')
print(df1)
预期输出:
df1:
0 1 2 3
0 Name Unit Attribute Date
1 a A 1 2014
2 b B 2 2015
3 c C 3 2016
4 d D 4 2017
5 e E 5 2018
df2:
0 1 2
0 Name Unit Date
1 a F 2019
2 b G 2020
3 e H 2021
4 f I 2022
df1 after operation:
0 1 2 3
0 Name Unit Attribute Date
1 a F 1 2019
2 b G 2 2020
3 c C 3 2016
4 d D 4 2017
5 e H 5 2021
我试过了:
df1.loc[[1,2,5],[1,3]] = df2.loc[[1,2,3],[1,2]]
print('df1:')
print(df1)
print('df2:')
print(df2)
但结果如下。有意想不到的楠。
df1:
0 1 2 3
0 Name Unit Attribute Date
1 a F 1 NaN
2 b G 2 NaN
3 c C 3 2016
4 d D 4 2017
5 e NaN 5 NaN
df2:
0 1 2
0 Name Unit Date
1 a F 2019
2 b G 2020
3 e H 2021
4 f I 2022
提前感谢任何提供帮助的人。
【问题讨论】: