[英]Changing df column format
I have the following dict
: 我有以下
dict
:
diction= [
{
"name": "x",
"no": 10,
"buy_sell": "buy",
"date": "10/07/2018"
}
,
{
"name": "y",
"no": 10,
"buy_sell": "sell",
"date": "11/07/2018"
}]
This has an undesired date format which is %d/%m/%Y
whereas I would like it to be %Y-%m-%d
. 这具有
%d/%m/%Y
的不期望的日期格式,而我希望它是%Y-%m-%d
。
What I have tried in order to change the format was to turn the dict
into a pd.DataFrame
and after that change the format of the column date
(and then turn it again to a dict
), here is what I tried: 为了更改格式,我尝试将
dict
转换为pd.DataFrame
,然后更改列date
的格式(然后再次将其转换为dict
),这是我尝试的方法:
tabla = pd.DataFrame(diction)
tabla['date'] = pd.to_datetime(tabla['date'])
tabla['date'] = tabla['date'].dt.strftime('%Y-%m-%d')
I don't know why it seems to be confusing the day with the month and is throwing out the output: 我不知道为什么它将日期和月份弄糊涂了,并丢弃了输出:
buy_sell date name no
0 buy 2018-10-07 x 10
1 sell 2018-11-07 y 10
My desired output would be: 我想要的输出将是:
buy_sell date name no
0 buy 2018-07-10 x 10
1 sell 2018-07-11 y 10
with the format %Y-%m-%d
. 格式为
%Y-%m-%d
。
If all you want to do is to change the format of the dates in the dictionaries you could simply: 如果您要做的只是更改字典中日期的格式,您可以:
for d in diction:
d['date'] = '{}-{}-{}'.format(d['date'][6:10], d['date'][3:5], d['date'][:2])
No need for pandas and converting data twice. 无需熊猫,也无需两次转换数据。
When you parse the dates, you could use 解析日期时,可以使用
pd.to_datetime(df.date, dayfirst=True)
instead. 代替。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.