在pandas中如何将一列拆分为两列

2024-10-04 03:16:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下一个数据帧

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,如下所示:

^{pr2}$

我用熊猫来读取数据

我试着从一个每月的数据库中计算日均数,每天的数据每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  

Tags: csv数据数据库dataframepandasreaddata方式
1条回答
网友
1楼 · 发布于 2024-10-04 03:16:49

这里是一个link与之前回答过的非常相似的问题,希望对您有所帮助。在您的例子中,可以按空格分隔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

希望这能解决你的问题,这是输出。在

^{pr2}$

相关问题 更多 >