numpy数组的元素作为具有相同索引的自己的 pandas 行 [英] Elements of numpy array as own pandas row with same index
本文介绍了numpy数组的元素作为具有相同索引的自己的 pandas 行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有numpy数组作为列中值的pandas DataFrame.我想将每个元素转换为具有相同日期的行:
I have a pandas DataFrame with numpy arrays as values in a column. I would like to turn each element to a row with the same date:
我的DataFrame看起来像这样:
My DataFrame looks like this:
date website+
0 2014-11-26 [A]
238 2015-12-20 [B, C]
297 2016-02-17 [D]
303 2016-02-23 [E, F, G]
我想要:
date website+
0 2014-11-26 [A]
238 2015-12-20 [B]
2015-12-20 [C]
297 2016-02-17 [D]
303 2016-02-23 [E]
2016-02-23 [F]
2016-02-23 [G]
只要日期保持不变,索引就不重要.我找到了一种将每个条目都变成一列的解决方案,但这并不是我想要的.
The index is not important as long as the date stays the same. I have found a solution to turn each entry into a column, but thats not exactly what I want.
推荐答案
如果第一列已在索引中,则可以使用以下内容:
If your first column is already in index, then you can use the following:
df.set_index('date', append=True)['website+']\
.apply(pd.Series).stack().reset_index(level=-1, drop=True)\
.to_frame(name='website+')
输出:
website+
date
0 2014-11-26 A
238 2015-12-20 B
2015-12-20 C
297 2016-02-17 D
303 2016-02-23 E
2016-02-23 F
2016-02-23 G
这篇关于numpy数组的元素作为具有相同索引的自己的 pandas 行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文