简体   繁体   English

使用 pandas 根据来自另一个 dataframe 的行值填充列值

[英]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.

相关问题 根据Pandas中第二列的条件,用另一行的同一列的值填充特定行的列中的值 - Fill values in a column of a particular row with the value of same column from another row based on a condition on second column in Pandas 根据pandas DataFrame中的另一列填充缺失值 - Fill missing values based on another column in a pandas DataFrame 根据另一数据框行的值pandas填充数据框行的值 - Fill DataFrame row values based on another dataframe row's values pandas 如何根据另外两个数据帧的值填充 Pandas 数据帧 - How to fill the Pandas Dataframe based on values from another two dataframes 根据列名乘以 pandas dataframe 的行,使用另一个 dataframe 的值 - Multiply row of pandas dataframe based on column name, using values of another dataframe Pandas DataFrames:如何根据另一个数据帧列中的值使用现有数据帧中的索引值定位行? - Pandas DataFrames: How to locate rows using index values in existing dataframe based on values from another dataframe column? Pandas 基于另一个 dataframe 将多个列和行值设置为 nan - Pandas Set multiple column and row values to nan based on another dataframe Pandas:根据另一个数据框中的值更新数据框中的多列 - Pandas : Updating multiple column in a dataframe based on values from another dataframe 如何根据 Pandas 数据框中的另一列值填充列中的缺失值? - How to fill missing values in a column based on another column values in a Pandas dataframe? 根据行值将单元格从一个 Pandas 数据帧覆盖到另一个 - overwriting cells from one pandas dataframe to another based on row values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM