简体   繁体   English

如何将更长的列表附加到数据框

[英]How to append a longer list to dataframe

I wanna append a longer list to dataframe .But get an error ValueError: Length of values (4) does not match length of index (3)我想在数据帧中附加一个更长的列表。但是得到一个错误 ValueError: Length of values (4) does not match length of index (3)

import pandas as pd

df = pd.DataFrame({'Data': ['1', '2', '3']})

df['Data2'] =['1', '2', '3', '4']

print(df)

How can I fix it .我该如何解决。

Use DataFrame.reindex for add new rows by maximal length by new list or original DataFrame, if length of list should be changed, sometimes same length or sometimes length is shorter:使用DataFrame.reindex通过新列表或原始数据帧的最大长度添加新行,如果列表的长度应该改变,有时长度相同或有时长度更短:

df = pd.DataFrame({'Data': ['1', '2', '3']})

L = ['1', '2', '3', '4']

df = df.reindex(range(max(len(df), len(L))))
df['Data2'] = L
print (df)
  Data Data2
0    1     1
1    2     2
2    3     3
3  NaN     4

If always is length of list longer:如果总是列表的长度更长:

df = df.reindex(range(len(L)))
df['Data2'] = L

You can try using pd.concat here but convert your list to a Series then use pd.concat您可以尝试在此处使用pd.concat但将您的列表转换为Series然后使用pd.concat

l = ['1', '2', '3', '4']
pd.concat([df, pd.Series(l, name='Data2')], axis=1)

  Data Data2
0    1     1
1    2     2
2    3     3
3  NaN     4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM