[英]How split a column in two columns in pandas
我有下一個數據框
data=read_csv('enero.csv')
data
Fecha DirViento MagViento
0 2011/07/01 00:00 318 6.6
1 2011/07/01 00:15 342 5.5
2 2011/07/01 00:30 329 6.6
3 2011/07/01 00:45 279 7.5
4 2011/07/01 01:00 318 6.0
5 2011/07/01 01:15 329 7.1
6 2011/07/01 01:30 300 4.7
7 2011/07/01 01:45 291 3.1
如何將Fecha列拆分為兩列,例如獲取一個dataframe如下:
Fecha Hora DirViento MagViento
0 2011/07/01 00:00 318 6.6
1 2011/07/01 00:15 342 5.5
2 2011/07/01 00:30 329 6.6
3 2011/07/01 00:45 279 7.5
4 2011/07/01 01:00 318 6.0
5 2011/07/01 01:15 329 7.1
6 2011/07/01 01:30 300 4.7
7 2011/07/01 01:45 291 3.1
我正在使用熊貓來讀取數據
我嘗試從每月數據庫中計算每日平均值,每 15 分鍾記錄一次每日數據。 為此,請使用 pandas 並對列進行分組:日期和時間以獲取數據框,如下所示:
Fecha Hora
2011/07/01 00:00 -4.4
00:15 -1.7
00:30 -3.4
2011/07/02 00:00 -4.5
00:15 -4.2
00:30 -7.6
2011/07/03 00:00 -6.3
00:15 -13.7
00:30 -0.3
有了這個外觀,我得到以下信息
grouped.mean()
Fecha DirRes
2011/07/01 -3
2011/07/02 -5
2011/07/03 -6
以下是之前已經回答的非常相似的問題的鏈接 ,希望它有用。 在您的情況下,您可以按空格拆分Fecha中的內容,並構造字符串的第二部分列表。 然后將內容添加到插入的新列中
import pandas as p
t = p.read_csv('test2.csv')
#store into a data frame
df = p.DataFrame(t)
#update the fecha col value and create new col hora
lista = [item.split(' ')[2] for item in df['Fecha']]
listb = p.Series([item.split(' ')[0] for item in df['Fecha']])
df['Fecha'].update(listb)
df['Hora'] = lista
#change Hora position
#I am not sure whether this is efficient or not
#as I am also quite new to Pandas
col = df.columns.tolist()
col = col[-1:]+col[:-1]
col[0], col[1] = col[1], col[0]
df = df[col]
print df
希望這可以解決您的問題,這是輸出。
Fecha Hora DirViento MagViento
0 2011/07/01 00:00 318 6.6
1 2011/07/01 00:15 342 5.5
2 2011/07/01 00:30 329 6.6
3 2011/07/01 00:45 279 7.5
4 2011/07/01 01:00 318 6.0
5 2011/07/01 01:15 329 7.1
6 2011/07/01 01:30 300 4.7
7 2011/07/01 01:45 291 3.1
如果某些日期行沒有小時格式怎么辦?
"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.