Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫:动态添加行、列和输入值_Python_Pandas - Fatal编程技术网

Python 熊猫:动态添加行、列和输入值

Python 熊猫:动态添加行、列和输入值,python,pandas,Python,Pandas,我正在使用一个大型数据集,该数据集迭代地获取特定父URL的n个子URL 我最初使用excel记录数据(实际测试我的代码的工作情况)。但是后来发现这个想法不值得,因为输出数据太大了 例如: 我有两组数据: amazon.com: ['a','b','c','d','e'] a : ['k','j','e','f'] 在第一种情况下,amazon.com是父URL,值列表是它的子URL 在下一种情况下,a成为父URL,值列表是它的子URL 现在我真正需要的是获得如下数据帧:

我正在使用一个大型数据集,该数据集迭代地获取特定父URL的n个子URL

我最初使用excel记录数据(实际测试我的代码的工作情况)。但是后来发现这个想法不值得,因为输出数据太大了

例如: 我有两组数据:

amazon.com: ['a','b','c','d','e']
a         : ['k','j','e','f']
  • 在第一种情况下,
    amazon.com
    是父URL,值列表是它的子URL
  • 在下一种情况下,
    a
    成为父URL,值列表是它的子URL
现在我真正需要的是获得如下数据帧:

               a    b    c    d    e    k    j    f
 amazon.com    1    1    1    1    1
     a                             1    1    1    1
其中1可以假设为一个值,表示say
a是amazon.com的子项

现在的问题是我没有上面显示的数据。它们是在我爬过网站时动态获取的

因此,流程将是:

Open a website URL
records the URL (parent URL - this is where we get the URL)
records all the URLs present in the page (child URL - this is where we get all the child URLs corresponding to the parent URL and hence can populate our list/dictionary and hence the dataframe)
可以注意到,没有找到重复的列标题

有人能帮我解决这个问题吗?

希望这会有帮助:

xx = {
    'amazon.com': ['a','b','c','d','e'],
    'a'         : ['k','j','e','f']
}
all_vals = [item for key,items in xx.items() for item in items]
all_vals = sorted(set(all_vals))
df = pd.DataFrame(index=xx.keys(),columns=all_vals)

def is_exist(idx,col):
    ret = col in xx[idx]
    return int(ret)

for idx in df.index:
    for col in df.columns:
        df.loc[idx, col] = is_exist(idx, col)

df
希望这将有助于:

xx = {
    'amazon.com': ['a','b','c','d','e'],
    'a'         : ['k','j','e','f']
}
all_vals = [item for key,items in xx.items() for item in items]
all_vals = sorted(set(all_vals))
df = pd.DataFrame(index=xx.keys(),columns=all_vals)

def is_exist(idx,col):
    ret = col in xx[idx]
    return int(ret)

for idx in df.index:
    for col in df.columns:
        df.loc[idx, col] = is_exist(idx, col)

df

非常感谢!那确实帮了我很大的忙。但我所需要的恰恰是->在每次迭代期间,动态填充与行关联的
行和
列。每一行都必须添加为
新索引
,相应的列值应作为
新列标题
输入,该标题在现有数据框中不应重复。很抱歉出现不一致的情况。但是我知道你所描述的和我提供的代码非常相似,你可以根据需要修改一下。非常感谢!那确实帮了我很大的忙。但我所需要的恰恰是->在每次迭代期间,动态填充与行关联的
行和
列。每一行都必须添加为
新索引
,相应的列值应作为
新列标题
输入,该标题在现有数据框中不应重复。很抱歉出现不一致的情况。但是我想你所描述的和我提供的代码非常相似,你可以根据需要修改一下。