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

标签 python pandas

我有以下数据帧,想要将其拆开,生成一系列 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/

相关文章:

python - 如何配置 Django 网站以使用 Apache VirtualHosts?

python - 当一个模块被导入两次时会发生什么?

python - Pandas Groupby 将函数应用于组

python - 如何在条件匹配三行的情况下迭代pandas数据框中的选定行?

python - Pylint 提示 "no value for argument ' cls'”

python - K-Arms Bandit Epsilon-贪心策略

Python 日期时间转换

python - PyQt:使用线程访问对象

python - Pandas /Python : How to create new column based on values from other columns and apply extra condition to this new column

python Pandas : Create a new column with values in English by converting values stored in a different column in Chinese traditional