python - pandas.DataFrame 根据另一个 DataFrame 进行切片

标签 python pandas

如何根据df1和df2创建df3?

df1 = pd.DataFrame([[1,2,3],[10,20,30],[100,200,300]], index=['a','b','c'],columns=['A','B','C'])
df2 = pd.DataFrame([['A','C'],['B','A'],['C','B']],index=['a','b','c'],columns=[0,1])
df3 = pd.DataFrame([[1,3],[20,10],[300,200]], index=['a','b','c'],columns=[0,1])

这是我的代码,

df1.apply(lambda x: x.loc[df2.loc[x.name,:]], axis=1)

这是 df1

df1

这是 df2

df2

这是 df3

enter image description here

最佳答案

似乎你可以使用 df2 在 stack 之后进行 lookup

s=df2.stack()
s
Out[321]: 
a  0    A
   1    C
b  0    B
   1    A
c  0    C
   1    B
dtype: object
pd.Series(df1.lookup(s.index.get_level_values(0),s),index=s.index).unstack()
Out[322]: 
     0    1
a    1    3
b   20   10
c  300  200

或者使用应用

df2.apply(lambda x : df1.loc[x.name,x].values,axis=1)
Out[327]: 
     0    1
a    1    3
b   20   10
c  300  200

关于python - pandas.DataFrame 根据另一个 DataFrame 进行切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52176573/

相关文章:

python - 在 Python 中将数据写入文件

python - jinja2.exceptions.UndefinedError - 没有属性 'favicon.ico'

python - 计算后将 Groupby 百分比添加到 Dataframe

python - 偏移数据框引用的最Pythonic方法?

python - Pandas :如何识别具有 dtype 对象但混合类型项目的列?

python - Django 。从 HDD 检索并打开 zip 文件

python - 从父类继承的孙子 - Python

python - 使用 pyramid_tm 时,SQLAlchemy session.begin_nested() 应该与 transaction.commit() 一起提交吗?

python - 如何查找二维数组的按列唯一元素及其频率

python - 如何根据连续索引拆分 DataFrame?