[英]fill column values based on row values from another dataframe using pandas
I basically have this我基本上有这个
first
0 bar
1 bar
2 foo
3 foo
bar foo
0 a b
I want to insert value in dataframe 2 to dataframe 1, so the final result should be something like this我想在 dataframe 2 中插入值到 dataframe 1,所以最终结果应该是这样的
first
0 a
1 a
2 b
3 b
You can simply use replace
like so:您可以像这样简单地使用replace
:
>>> df1.replace(df2.transpose()[0])
first
0 a
1 a
2 b
3 b
If you want to check efficiency:如果要检查效率:
%timeit df1.replace(df2.transpose()[0])
711 µs ± 18.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
You can use join on a transposed df2:您可以在转置的 df2 上使用 join:
df1.set_index('first').join(df2.T)
Out[11]:
0
bar a
bar a
foo b
foo b
Or with a dictionary:或者用字典:
df1['first'].map(df2.T.to_dict()[0])
Out[17]:
0 a
1 a
2 b
3 b
Name: first, dtype: object
Or with merge:或合并:
df1.merge(df2.T.reset_index(), left_on=['first'], right_on=['index'])
first index 0
0 bar bar a
1 bar bar a
2 foo foo b
3 foo foo b
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.