I have two lists whose no. of elements are not equal. I want to put these two lists in a csv whose heading is 'video' and 'image'. But as the elements of these 2 lists are not the same I got an error.
ValueError: All arrays must be of the same length
import pandas as pd
VID = ['00001', '05445', '987457', '15455']
IMG = ['00001', '05445', '987457']
df = pd.DataFrame(data={"video": VID, "image": IMG})
df.to_csv("./file.csv", sep=',',index=False)
CodePudding user response:
You can convert to Series
first:
import pandas as pd
VID = ['00001', '05445', '987457', '15455']
IMG = ['00001', '05445', '987457']
df = pd.DataFrame(data={"video": pd.Series(VID), "image": pd.Series(IMG)})
df.to_csv("./file.csv", sep=',',index=False)
More generic approach if many items:
names = ['video', 'image']
vals = [VID, IMG]
df = pd.DataFrame(dict(zip(names, map(pd.Series, vals))))
df.to_csv("./file.csv", sep=',',index=False)
CodePudding user response:
Suggestion 1:
Using None to create an "empty value"/null value
import pandas as pd
VID = ['00001', '05445', '987457', '15455']
IMG = ['00001', '05445', '987457', None]
df = pd.DataFrame(data={"video": VID, "image": IMG})
Suggestion 2:
import pandas as pd
VID = ['00001', '05445', '987457', '15455']
IMG = ['00001', '05445', '987457', '0']
df = pd.DataFrame(data={"video": VID, "image": IMG})
CodePudding user response:
Convert list to Series and it will work.
import pandas as pd
VID = ['00001', '05445', '987457', '15455']
IMG = ['00001', '05445', '987457']
df = pd.DataFrame({"video": pd.Series(VID), "image": pd.Series(IMG)})
video image
0 00001 00001
1 05445 05445
2 987457 987457
3 15455 NaN