[英]Splitting columns and reformat date using pandas
I have an object, slist
that I need to split, reformat the date, and export as a tab delimited file.我有一个 object,需要拆分、重新格式化日期并导出为制表符分隔文件的slist
。 For the splitting I think I'm tripping up understanding the first row?对于分裂,我认为我在理解第一行时会绊倒? Here is slist
:这是slist
:
I've tried the following:我尝试了以下方法:
df = pd.DataFrame(data=slist)
newdf['datetime','values'] = df['node_21_Depth_above_invert'].astype(str).str.split(' ',expand=True)
Which gives me something like this:这给了我这样的东西:
I've spent a ton of time trying to figure this out and I know there are a lot of other pandas questions about column splitting, but I've hit a wall and any insight would be helpful.我花了很多时间试图弄清楚这一点,我知道还有很多其他关于列拆分的 pandas 问题,但我遇到了困难,任何见解都会有所帮助。 Thanks!谢谢!
As you now have the datetime as row index, you can make it a data column by .reset_index()
and then rename the columns, as follows:由于您现在将日期时间作为行索引,因此您可以通过.reset_index()
将其设为数据列,然后重命名列,如下所示:
newdf = df.reset_index()
newdf.columns = ['datetime','values']
Test Data Preparation测试数据准备
slist = {'node_21_Depth_above_invert': {pd.Timestamp('1998-01-01 01:00:00'): 1.0, pd.Timestamp('1998-01-01 02:00:00'): 1.519419550895691, pd.Timestamp('1998-01-01 03:00:00'): 2.0, pd.Timestamp('1998-01-01 04:00:00'): 2.0, pd.Timestamp('1998-01-01 05:00:00'): 2.0}}
df = pd.DataFrame(data=slist)
print(df)
node_21_Depth_above_invert
1998-01-01 01:00:00 1.00000
1998-01-01 02:00:00 1.51942
1998-01-01 03:00:00 2.00000
1998-01-01 04:00:00 2.00000
1998-01-01 05:00:00 2.00000
Run New Codes运行新代码
newdf = df.reset_index()
newdf.columns = ['datetime','values']
Result:结果:
print(newdf)
datetime values
0 1998-01-01 01:00:00 1.00000
1 1998-01-01 02:00:00 1.51942
2 1998-01-01 03:00:00 2.00000
3 1998-01-01 04:00:00 2.00000
4 1998-01-01 05:00:00 2.00000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.