我的问题是如何使用DataFrame的append()方法将行干净地附加到DataFrame?
根据docs,append()将“DataFrame或Series / dict-like对象或其列表”作为参数。鉴于描述,我想到的是这样应该是可能的,但我找不到合适的语法:
df = pd.DataFrame(columns=('x', 'y', 'label'))
df.append([2, 4, 1]) # Does not work
我可以在df.loc[len(df)] = [4, 4, 1]
附加一行,但这不是很干净。
答案 0 :(得分:2)
DataFrame.append
需要Series
或DataFrame
与index
相同columns names
或与df
相同{/ 1}}:
df1 = pd.DataFrame([[2, 4, 1]], columns=('x', 'y', 'label'))
print (df1)
x y label
0 2 4 1
df = df.append([pd.Series([4, 4, 1], index = df.columns)], ignore_index=True)
df = df.append(df1, ignore_index=True)
#your solution
df.loc[len(df)] = [4, 4, 1]
print (df)
x y label
0 4.0 4.0 1.0
1 2.0 4.0 1.0
2 4.0 4.0 1.0
#dont align because default columns names
df = df.append([[4, 4, 1]])
print (df)
x y label 0 1 2
0 NaN NaN NaN 4.0 4.0 1.0
但是如果是默认列名:
df = pd.DataFrame(columns=range(3))
print (df)
Empty DataFrame
Columns: [0, 1, 2]
Index: []
df = df.append([[4, 4, 1]])
print (df)
0 1 2
0 4.0 4.0 1.0
答案 1 :(得分:0)
您也可以执行以下操作:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication24
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
string[] Paths = {
"Home/Girls/Smoll",
"Home/Girls/Pige",
"Home/Girls/Manualy",
"Home/Man/Smoll",
"Home/Man/Pig",
"index/domain/index",
"index/ur"
};
List<List<string>> splitPaths = Paths.Select(x => x.Split(new char[] { '/' }).ToList()).ToList();
TreeNode node = new TreeNode();
RecursiveAdd(splitPaths, node);
treeView1.Nodes.Add(node);
treeView1.ExpandAll();
}
public void RecursiveAdd(List<List<string>> splitPaths, TreeNode node)
{
var groups = splitPaths.GroupBy(x => x[0]).ToList();
foreach (var group in groups)
{
TreeNode childNode = node.Nodes.Add(group.Key);
List<List<string>> children = group.Where(x => x.Count() > 1).Select(x => x.Skip(1).ToList()).ToList();
RecursiveAdd(children, childNode);
}
}
}
}
真的没办法少于那个。