[英]How to fill in columns from lists/arrays into an empty Pandas dataframe with only column names
I have a dataframe with several column names.我有一个 dataframe 有几个列名。 As and when I get data for each column, I have to create rows.
当我获取每一列的数据时,我必须创建行。 I don't have all the row data available in one place.
我没有在一个地方提供所有行数据。 As and when I get data for a column in a particular row, I will fill it
当我获取特定行中的列的数据时,我将填充它
In this example below, I have created an empty dataframe and and I am trying to fill in a particular column with a set of values.在下面的这个例子中,我创建了一个空的 dataframe 并且我试图用一组值填充一个特定的列。 This is not working.
这是行不通的。
import pandas as pd
import numpy as np
col_names = ['ampere', 'freq', 'count']
dataf = pd.DataFrame(columns = col_names)
freq = np.arange(0.6,2.6,0.1).tolist()
#Add the list of frequencies to the frequency column
dataf['freq'].iloc[1:len(freq)] = freq
The error I am getting is我得到的错误是
ValueError: cannot copy sequence with size 20 to array axis with dimension 0 ValueError:无法将大小为 20 的序列复制到维度为 0 的数组轴
You're almost there!您快到了! There is no need for the
iloc
-indexing.不需要
iloc
索引。
So just change your last line to所以只需将您的最后一行更改为
dataf['freq'] = freq
and it should work as expected.它应该按预期工作。
If you want to keep adding more rows from different lists, as you mentioned in the comment, you can use following code snippet:如果您想继续从不同的列表中添加更多行,正如您在评论中提到的,您可以使用以下代码片段:
import pandas as pd
import numpy as np
col_names = ['ampere', 'freq', 'count']
dataf = pd.DataFrame(columns = col_names)
freq = np.arange(0.6,2.6,0.1).tolist()
#Add the list of frequencies to the frequency column
dataf['freq'] = freq
freq2 = np.arange(7,70,1).tolist()
for i, value in enumerate(freq2, len(dataf)):
dataf.loc[i] = [np.nan, value, np.nan]
I hope this helps to solve your problem.我希望这有助于解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.