如何将所有dataframe列合并为一列? [英] How to concatenate all dataframe column into one column?
本文介绍了如何将所有dataframe列合并为一列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个大致像这样的数据框:
I have a dataframe that looks roughly like:
2020-01-01 2020-01-02 2020-01-03 2020-01-05
00:00:00 11 47 54 10
01:00:00 12 49 46 22
...
23:00:00 15 34 22 40
预期输出...
2020-01-01 00:00:00 11
2020-01-01 01:00:00 12
...
2020-01-01 23:00:00 12
2020-01-02 00:00:00 47
2020-01-02 01:00:00 49
...
2020-01-01 23:00:00 34
...
推荐答案
使用 DataFrame.pop
用于提取列:
Use DataFrame.melt
with convert index to column, then convert columns to datetimes and timedeltas and join together with DataFrame.pop
for extract columns:
df = df.reset_index().melt('index')
df.index = pd.to_datetime(df.pop('variable')) + pd.to_timedelta(df.pop('index'))
#alternative with join strings
#df.index = pd.to_datetime(df.pop('variable') + ' ' + df.pop('index'))
print (df)
value
2020-01-01 00:00:00 11
2020-01-01 01:00:00 12
2020-01-01 23:00:00 15
2020-01-02 00:00:00 47
2020-01-02 01:00:00 49
2020-01-02 23:00:00 34
2020-01-03 00:00:00 54
2020-01-03 01:00:00 46
2020-01-03 23:00:00 22
2020-01-05 00:00:00 10
2020-01-05 01:00:00 22
2020-01-05 23:00:00 40
如果未使用pop
是必要的,请通过 DataFrame.drop
:
If pop
is not used is necessary remove columns by DataFrame.drop
:
df = df.reset_index().melt('index')
df.index = pd.to_datetime(df['variable']) + pd.to_timedelta(df['index'])
df = df.drop(['index','variable'], axis=1)
使用 DataFrame.unstack
并将MultiIndex
与map
结合在一起并转换为DatetimeIndex
,输出为Series
:
Another idea with DataFrame.unstack
and join MultiIndex
with map
and convert to DatetimeIndex
, output is Series
:
s = df.unstack()
s.index = pd.to_datetime(s.index.map('{0[0]} {0[1]}'.format))
print (s)
2020-01-01 00:00:00 11
2020-01-01 01:00:00 12
2020-01-01 23:00:00 15
2020-01-02 00:00:00 47
2020-01-02 01:00:00 49
2020-01-02 23:00:00 34
2020-01-03 00:00:00 54
2020-01-03 01:00:00 46
2020-01-03 23:00:00 22
2020-01-05 00:00:00 10
2020-01-05 01:00:00 22
2020-01-05 23:00:00 40
dtype: int64
这篇关于如何将所有dataframe列合并为一列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文