python中数据框同时加两列_如何在同一数据框(Python,Pandas)中合并1中的2列?...

I'm following tutorial of Wes McKinney on using pandas/python for trading backtesting (http://youtu.be/6h0IVlp_1l8).

After pd.read_csv(...) he's using 'dt' (datetime) column as index of dataframe.

df.index = pd.to_datetime(df.pop('dt'))

However, my data has 2 separate columns, 'Date[G]' and 'Time[G]' and the data inside is something like 04-JAN-2013,00:00:00.000 (comma-separated).

How do i modify that line of code in order to do the same? I.e. merge two columns within one data frame, and then delete it. Or is there a way to do that during read_csv itself?

Thanks for all answers.

解决方案

You should be able to concat two columns using apply() and then use to_datetime().

To remove columns from dataframe use drop() or just select columns you need:

df['dt'] = pd.to_datetime(df.apply(lambda x: x['Date[G]'] + ' ' + x['Time[G]'], 1))

df = df.drop(['Date[G]', 'Time[G]'], 1)

# ..or

# df = df[['dt', ...]]

df.set_index('dt', inplace = True)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值