[英]Removing the words DateTimeIndex from a list of dates
我在 Pandas 數據框中有多個日期列表,格式如下:
col1 col2
1 [DatetimeIndex(['2018-10-01', '2018-10-02',
'2018-10-03', '2018-10-04'],
dtype='datetime64[ns]', freq='D')
我想dtype='datetime64[ns]', freq='D'
DatetimeIndex
和dtype='datetime64[ns]', freq='D'
,把列表變成一個集合。 我要尋找的格式是: {'2018-10-01', '2018-10-02', '2018-10-03', '2018-10-04}
Pandas 並非旨在將集合保存在系列值中,因此強烈不鼓勵您執行此操作。 一個更好的主意,特別是如果您在每個DatetimeIndex
系列值中有一致數量的值,是加入額外的列:
D = pd.DatetimeIndex(['2018-10-01', '2018-10-02', '2018-10-03', '2018-10-04'],
dtype='datetime64[ns]', freq='D')
df = pd.DataFrame({'col1': [1], 'col2': [D]})
df = df.join(pd.DataFrame(df.pop('col2').values.tolist()))
print(df)
col1 0 1 2 3
0 1 2018-10-01 2018-10-02 2018-10-03 2018-10-04
如果你真的想要一個set
作為每個系列的值,你可以通過map
+ set
這樣做:
df['col2'] = list(map(set, df['col2'].values))
print(df)
col1 col2
0 1 {2018-10-01 00:00:00, 2018-10-02 00:00:00, 201...
你有沒有嘗試過:
set(index_object.tolist())
我懷疑這會返回一組時間戳對象而不是字符串,因此取決於您的用例是否這是您想要的
如果是你想要的字符串,你可以修改代碼如下:
set(index_object.dt.strftime("%Y-%m-%d").tolist())
對於您的特定格式(我不一定贊成!),您可以嘗試以下操作:
import itertools
string_lists = col2.apply(lambda x: x.dt.strftime("%Y-%m-%d").tolist())
unique_set = set(itertools.chain.from_iterable(string_lists.tolist()))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.