我有一个这样的数据框:
desc id info
[a,b,c] 2 type
[u,v,w] 18 tail
三列:desc,id,info和desc是一个列表。我想要这个:
des id info
a 2 type
b 2 type
c 2 type
u 18 tail
v 18 tail
w 18 tail
这意味着将列表列分解为多行,其他列没有更改。 我真的不知道该怎么做......
答案 0 :(得分:4)
这是一种方式
df.set_index(['id', 'info']).desc.apply(pd.Series).stack()\
.reset_index(name = 'desc').drop('level_2', axis = 1)
id info desc
0 2 type a
1 2 type b
2 2 type c
3 18 tail u
4 18 tail v
5 18 tail w
答案 1 :(得分:2)
我记得这应该来自piRSquared或cᴏʟᴅsᴘᴇᴇᴅ,但找不到链接...
function index($type="deposit", $limit_from=0)
{
$limit_from = ($this->uri->segment(4)) ? $this->uri->segment(4) : 0;
$total_records = $this->Expense->get_total_rows($type);
$data['controller_name'] = $this->get_controller_name();
$lines_per_page = 3;
$data[$type.'s'] = $this->Expense->get_records($lines_per_page, $limit_from, $type);
$config['base_url'] = base_url('index.php/expenses/index/'.$type);
$config['total_rows'] = $total_records;
$config['per_page'] = 3;
$config["uri_segment"] = 4;
// $choice = $total_records / $config['per_page'];
// $config['num_links'] = round($choice);
$config['use_page_numbers'] = TRUE;
$config['first_url'] = base_url('index.php/expenses/index/'.$type.'/1');
$this->pagination->initialize($config);
$data["links"] = $this->pagination->create_links();
$this->load->view('expenses/'.$type, $data);
$this->_remove_duplicate_cookies();
}
答案 2 :(得分:1)
您可以展平desc
列,repeat
其他两列,然后将它们连接起来:
pd.concat([
pd.Series([e for s in df.desc for e in s], name='desc'),
df.drop('desc', 1).apply(lambda col: col.repeat(df.desc.str.len())).reset_index(drop=True)
], axis=1)
#desc id info
#0 a 2 type
#1 b 2 type
#2 c 2 type
#3 u 18 tail
#4 v 18 tail
#5 w 18 tail
答案 3 :(得分:1)
你可以
In [1631]: (df.loc[df.index.repeat(df.desc.str.len())]
.assign(desc=[v for x in df.desc.values for v in x]))
Out[1631]:
desc id info
0 a 2 type
0 b 2 type
0 c 2 type
1 u 18 tail
1 v 18 tail
1 w 18 tail