我有两个列表都包含我要写入csv文件的值。所以我做的第一件事就是将我的csv文件导入到pandas dataframe中。然后我想写两个新列并将这两个列添加到新列中。我的代码如下。请注意,原始csv文件已存在几个列。
import pandas as pd
df = pd.read_csv('1.csv') ## 1.csv is the csv file I want to import.
a = [0.001, 5, 38, 70, 101, 140, 190]
b= [35, 65, 100, 160, 170, 200]
df['Start Time'] = a
df['End Time'] = b
df.to_csv('1.csv')
但是,当我运行此代码时,它给了我一个错误,如下所示,
ValueError: Length of values does not match length of index
如果有人知道如何解决这个问题,请告诉我。感谢!
答案 0 :(得分:2)
我认为您首先需要创建Series
,但如果长度与NaN
的长度不同,则df
中的所有最后一个值都会获得DataFrame
:
df['Start Time'] = pd.Series(a, index = df.index[:len(a)])
df['End Time'] = pd.Series(b, index = df.index[:len(b)])
样品:
df = pd.DataFrame({'a':range(10)})
a = [0.001, 9, 46, 84, 122, 153, 198]
b= [39, 76, 114, 150, 158, 210]
df['Start Time'] = pd.Series(a, index = df.index[:len(a)])
df['End Time'] = pd.Series(b, index = df.index[:len(b)])
print (df)
a Start Time End Time
0 0 0.001 39.0
1 1 9.000 76.0
2 2 46.000 114.0
3 3 84.000 150.0
4 4 122.000 158.0
5 5 153.000 210.0
6 6 198.000 NaN
7 7 NaN NaN
8 8 NaN NaN
9 9 NaN NaN
答案 1 :(得分:0)
还可以尝试将a和b的数据类型更改为字符串。这样,NAN值将留为空白。
import pandas as pd
df = pd.read_csv('1.csv') ## 1.csv is the csv file I want to import.
a = [0.001, 5, 38, 70, 101, 140, 190]
b = [35, 65, 100, 160, 170, 200]
df['Start Time'] = str(a)
df['End Time'] = str(b)
df.to_csv('1.csv')