我有一个熊猫系列:
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 Series (其中数组自然被索引)或numpy数组。
对于dataframe,为了组合两个列,您可以使用:
df["newcolumn"] = df[['columnA','columnB']].astype(str).sum(axis=1)但我对如何通过熊猫系列来实现这一点感到困惑。
发布于 2016-08-27 03:53:41
假设你从你的系列开始:
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发布于 2016-08-27 04:18:45
您可以使用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: objecthttps://stackoverflow.com/questions/39173560
复制相似问题