作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下数据帧,想要将其拆开,生成一系列 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 个元素,并将它们组装在一起作为新构建的系列的索引和数据。
最佳答案
这是枢轴
问题
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/
我是一名优秀的程序员,十分优秀!