在panda中将列元素转换为列名(下)

2024-10-01 11:19:26 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我之前提出的a question。你知道吗

如何转换以下行:

   time1,stockA,bid,1
   time2,stockA,ask,1.1
   time3,stockB,ask,2.1
   time4,stockB,bid,2.0
   time5,stockA,bid,1.1
   time6,stockA,ask,1.2
   time7,stockA,high,1.5
   time8,stockA,low,0.5

到以下panda dataframe

  time     stock       bid    ask    high    low
  time1    stockA      1      
  time2    stockA             1.1
  time3    stockB             2.1
  time4    stockB      2.0    
  time5    stockA      1.1
  time6    stockA             1.2
  time7    stockA                     1.5
  time8    stockA                            0.5

感谢您的帮助!你知道吗


Tags: asklowquestionhighbidtime1time2time3
2条回答

我的方法是将csv读入2个df,一个有bid-ask列,一个没有bid-ask列:

In [99]:

t="""time1,stockA,bid,1
 time2,stockA,ask,1.1
 time3,stockB,ask,2.1
 time4,stockB,bid,2.0
 time5,stockA,bid,1.1
 time6,stockA,ask,1.2
 time7,stockA,high,1.5
 time8,stockA,low,0.5"""
​
df = pd.read_csv(io.StringIO(t), header=None, names=['time', 'stock', 'bid', 'ask'], usecols=['time', 'stock'])
df
Out[99]:
     time   stock
0   time1  stockA
1   time2  stockA
2   time3  stockB
3   time4  stockB
4   time5  stockA
5   time6  stockA
6   time7  stockA
7   time8  stockA

对于第二个df,我们可以调用^{}来旋转df以从'bid'值创建列,我们需要重置索引,然后我们可以将2个df合并在一起以获得您想要的结果,如果需要,您可以用空字符串替换NaN值:

In [102]:

df_new = pd.read_csv(io.StringIO(t), header=None, names=['time', 'stock', 'bid', 'ask'], usecols=['time','bid','ask'])
df_new = df_new.pivot(columns ='bid', values='ask', index='time')
df_new = df_new.reset_index()
df = df.merge(df_new)
df
Out[102]:
     time   stock  ask  bid  high  low
0   time1  stockA  NaN  1.0   NaN  NaN
1   time2  stockA  1.1  NaN   NaN  NaN
2   time3  stockB  2.1  NaN   NaN  NaN
3   time4  stockB  NaN  2.0   NaN  NaN
4   time5  stockA  NaN  1.1   NaN  NaN
5   time6  stockA  1.2  NaN   NaN  NaN
6   time7  stockA  NaN  NaN   1.5  NaN
7   time8  stockA  NaN  NaN   NaN  0.5

你要做的是旋转桌子。 以下方法导致时间和库存形成一个多指标

 df = pd.read_csv('prices.csv', header=None, names=['time', 'stock', 'type',   'prices'], 
                  index_col=['time', 'stock', 'type'])

In [1062]:

df
Out[1062]:
                    prices
time    stock   type    
time1   stockA  bid 1.0
time2   stockA  ask 1.1
time3   stockB  ask 2.1
time4   stockB  bid 2.0
time5   stockA  bid 1.1
time6   stockA  ask 1.2
time7   stockA  high1.5
time8   stockA  low 0.5

我认为数据帧应该是这样的。 那就做吧

In [1064]:

df.unstack()
Out[1064]:
                prices
type            ask bid high low
time    stock               
time1   stockA  NaN 1.0 NaN NaN
time2   stockA  1.1 NaN NaN NaN
time3   stockB  2.1 NaN NaN NaN
time4   stockB  NaN 2.0 NaN NaN
time5   stockA  NaN 1.1 NaN NaN
time6   stockA  1.2 NaN NaN NaN
time7   stockA  NaN NaN 1.5 NaN
time8   stockA  NaN NaN NaN 0.5

您可以使用df.fillna用您喜欢的任何东西填充nan。一般来说,将列值转换为列标题称为数据透视。.unstack透视多重索引的一个级别。您也可以检查.pivot。你能做到的

df.columns = df.columns.droplevel(0)

去掉列中包含每列“prices”的外层

相关问题 更多 >