Pandas:翻转DF范围的值和索引?

发布于 2025-02-13 20:00:42 字数 523 浏览 3 评论 0 原文

我正在尝试以这种方式翻转价值和索引:

df = pd.DataFrame({"day1":{"JOHN":"A","JANE":"B","JILL":"C"},"day2":{"JOHN":"A","JANE":"C","JILL":np.nan},"day3":{"JOHN":"C","JANE":"A","JILL":"B"}})
df
     day1   day2    day3
JOHN    A      A       C
JANE    B      C       A
JILL    C    NaN       B

寻找:

     day1    day2    day3
A    JOHN    JOHN    JANE
B    JANE    NaN     JILL
C    JILL    JANE    JOHN

我很难概念化如何解决这个问题。我的头脑跳动以某种方式旋转,但我什么都没到。

谢谢

I'm trying to flip values and index in this manner:

df = pd.DataFrame({"day1":{"JOHN":"A","JANE":"B","JILL":"C"},"day2":{"JOHN":"A","JANE":"C","JILL":np.nan},"day3":{"JOHN":"C","JANE":"A","JILL":"B"}})
df
     day1   day2    day3
JOHN    A      A       C
JANE    B      C       A
JILL    C    NaN       B

looking for:

     day1    day2    day3
A    JOHN    JOHN    JANE
B    JANE    NaN     JILL
C    JILL    JANE    JOHN

I'm having trouble conceptualizing how to tackle that. My mind jumps to pivoting somehow, but I'm not getting anywhere.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我的影子我的梦 2025-02-20 20:00:42

使用 将多索引的第一级转换为列和列 0 附加到 index ,因此可能使用 series.unstack 与transpose:

df = df.stack().reset_index(level=0).set_index(0, append=True)['level_0'].unstack().T
print (df)
   day1  day2  day3
0                  
A  JOHN  JOHN  JANE
B  JANE   NaN  JILL
C  JILL  JANE  JOHN

或使用 a>将索引转换为列,然后用

df = df.reset_index().melt('index').dropna().pivot('value','variable','index')
print (df)
variable  day1  day2  day3
value                     
A         JOHN  JOHN  JANE
B         JANE   NaN  JILL
C         JILL  JANE  JOHN

Use DataFrame.stack with convert first level of MultiIndex to column and column 0 append to Index, so possible use Series.unstack with transpose:

df = df.stack().reset_index(level=0).set_index(0, append=True)['level_0'].unstack().T
print (df)
   day1  day2  day3
0                  
A  JOHN  JOHN  JANE
B  JANE   NaN  JILL
C  JILL  JANE  JOHN

Or use DataFrame.melt with convert index to column and then remove missing values with DataFrame.pivot:

df = df.reset_index().melt('index').dropna().pivot('value','variable','index')
print (df)
variable  day1  day2  day3
value                     
A         JOHN  JOHN  JANE
B         JANE   NaN  JILL
C         JILL  JANE  JOHN
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文