在pandas中使用并更改csv文件的布局

2024-04-25 01:37:16 发布

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

我用pandas读取csv数据,现在我想更改数据集的布局。我的excel数据集如下所示:

enter image description here

我用df = pd.read_csv(Location2)运行代码

这就是我得到的:

enter image description here

我想为timeWatt及其值创建一个单独的列。你知道吗

我看了文件,但找不到能使它起作用的东西。你知道吗


Tags: 文件csv数据代码pandasdfreadtime
3条回答

似乎需要设置分隔两个字段的正确分隔符。尝试向参数中添加delimiter=";"

使用read_excel

df = pd.read_excel(Location2)

我认为在^{}中需要参数sep,因为默认分隔符是,

df = pd.read_csv(Location2, sep=';')

样品:

import pandas as pd
from pandas.compat import StringIO

temp=u"""time;Watt
0;00:00:00;50
1;01:00:00;45
2;02:00:00;40
3;00:03:00;35"""
#after testing replace 'StringIO(temp)' to 'filename.csv'
df = pd.read_csv(StringIO(temp), sep=";")
print (df)
       time  Watt
0  00:00:00    50
1  01:00:00    45
2  02:00:00    40
3  00:03:00    35

然后可以转换time^{}

df['time'] = pd.to_timedelta(df['time'])
print (df)
      time  Watt
0 00:00:00    50
1 01:00:00    45
2 02:00:00    40
3 00:03:00    35

print (df.dtypes)
time    timedelta64[ns]
Watt              int64
dtype: object

相关问题 更多 >