如何在pd.DataFrame(index=)中动态分配索引,因为它为每个行字段提供相同的索引,或者我们必须传递一个索引值列表?

2024-06-16 09:42:37 发布

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

例如: 新闻内容

{articles : [{'headline' : ..., 'url' : ..., 'body' : ...}, {'headline' : ..., 'url' : ..., 'body' : ...}, ...so on uptill 200 data points]}
df_news = pd.DataFrame()
for ix in news_dict['articles']:
       p = {'headline' : ix['headline'], 'url' : ix['url'], 'body' : ix['body']}
       df = pd.DataFrame(data = p, index = 0)
       df_news = df_news.append(df)

现在,上面的输出提供了一个附加的数据帧,其中所有行的索引都为0。另一种方法是“headline”:[ix['headline']],但它仍然将索引设为0

One can easily pass a list index = [1,2,3,...200] but it becomes cumber some for data upto 1000. 

我们如何动态地更新这样的索引

如果我没有传递索引,那么它会抛出一个错误: ValueError:如果使用所有标量值,则必须传递索引

我没有显示输出的数据,因为它很长。 输出:

    headline        url       body
0   headline_1      url_1     body_1
0   ....
0   

可以将示例输入用作:

sample_input : {'A':[{'a':1, 'b':2, 'c':3}, {'a':4,'b':5,'c':6}, {'a':20, 'b': 50, 'c': '30}]}

期望输出:

    a   b   c

0   1   2   3

1   4   5   6

2   20  50  30

a、b、c是列标题

0 1 2是指数


Tags: 数据url内容dataframedffordataindex