gpt4 book ai didi

python - pandas:将 DataFrame 拆分为 Series 会导致 NaN

转载 作者:行者123 更新时间:2023-11-30 22:05:18 25 4
gpt4 key购买 nike

我有以下数据帧,想要将其拆开,生成一系列 x 和一系列 y,其中 time 作为索引,value 作为数据:

   var  time  value
0 x 0 11
1 y 0 123
2 x 1 12
3 y 1 124
4 x 2 13
5 y 2 125

这是我的代码:

import pandas as pd

df = pd.DataFrame({
'time': [0,0,1,1,2,2],
'var': list('xyxyxy'),
'value': [11,123,12,124,13,125]})

for col in ['x', 'y']:
s = pd.Series(
data=df.loc[df['var'] == col, 'value'],
index=df.loc[df['var'] == col, 'time'],
name=col)
print(s)

这是输出:

time
0 11.0
1 NaN
2 12.0
Name: x, dtype: float64

time
0 NaN
1 123.0
2 NaN
Name: y, dtype: float64

但我希望这个系列是

time
0 11.0
1 12.0
2 13.0
Name: x, dtype: float64

time
0 123.0
1 124.0
2 125.0
Name: y, dtype: float64

显然 pandas 没有将时间轴与轴正确对齐。据我了解,每个 .loc 应该只返回相应的 3 个元素,并将它们组装在一起作为新构建的系列的索引和数据。

  1. 为什么这种情况没有发生?
  2. 获得所需结果的最简单方法是什么?

最佳答案

这是枢轴问题

s=df.pivot(*df.columns)
s
Out[56]:
time 0 1 2
var
x 11 12 13
y 123 124 125

#s['y'],s['x']

关于python - pandas:将 DataFrame 拆分为 Series 会导致 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53069953/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com