首页 文章

如何将索引“前缀”与Pandas系列中的数据相结合?有人创建一个numpy数组吗?

提问于
浏览
1

我有一个熊猫系列:

import pandas 
ser = pd.Series(...)
ser

idx1     23421535123415135
idx2     98762981356281343
idx3     394123942916498173
idx4     41234189756983411
...
idx50    123412938479283419

我想将索引附加到每个数据行的前面 . 我正在寻找的输出是:

idx1 23421535123415135
idx2 98762981356281343
idx3 394123942916498173
idx4 41234189756983411
...
idx50 123412938479283419

这可能是一个pandas系列(数组自然被索引)或numpy数组 .

对于数据框,为了组合两列,您使用:

df["newcolumn"] = df[['columnA','columnB']].astype(str).sum(axis=1)

但我很困惑如何用熊猫系列来完成这个任务 .

2 回答

  • 1

    假设您从系列开始:

    In [34]: s = pd.Series(data=[1, 2], index=['idx0', 'idx1'])
    

    那你可以做

    In [35]: t = s.reset_index()
    
    In [36]: t['index'].astype(str) + ' ' + t[0].astype(str)
    Out[36]: 
    0    idx0 1
    1    idx1 2
    dtype: object
    

    请注意,如果您不需要在两者之间引入空间,则更短:

    In [37]: s.reset_index().astype(str).sum(axis=1)
    Out[37]: 
    0    idx01
    1    idx12
    dtype: object
    
  • 1

    你可以使用pandas.series.str.cat

    In[8]:ser
    Out[8]: 
    idx0     23421535123415135
    idx1     98762981356281343
    idx2    394123942916498173
    idx3     41234189756983411
    dtype: int64
    
    In[9]:ser=pd.Series(ser.index.astype(str).str.cat(ser.astype(str),' '))
    
    In[10]:ser
    Out[10]: 
    0     idx0 23421535123415135
    1     idx1 98762981356281343
    2    idx2 394123942916498173
    3     idx3 41234189756983411
    dtype: object
    

相关问题