简体   繁体   English

Python:根据DataFrame中的列名创建新行

[英]Python: create new row based on column names in DataFrame

I would like to know how to make a new row based on the column names row in a python dataframe, and append it to the same dataframe. 我想知道如何根据python数据帧中的列名行创建一个新行,并将其附加到同一个数据帧。

example

df = pd.DataFrame(np.random.randn(10, 5),columns=['abx', 'bbx', 'cbx', 'acx', 'bcx'])

I want to create a new row based on the column names that gives: b | b | b | c | c | 我想根据列名称创建一个新行: b | b | b | c | c | b | b | b | c | c | by taking the middle char of the column name. 通过获取列名称的中间字符。

the idea is to use that new row, later, for multi-indexing the columns. 我的想法是稍后使用该新行来对列进行多索引。

I'm assuming this is what you want as you've not responded, we can append a new row by creating a dict from zipping the df columns and a list comprehension of the middle character (assuming that column name lengths are 3): 我假设这是你想要的,因为你没有回应,我们可以通过从压缩df列创建一个dict和中间字符的列表理解来append一个新行(假设列名长度为3):

In [126]:

df.append(dict(zip(df.columns, [col[1] for col in df])), ignore_index=True)
Out[126]:
          abx         bbx        cbx        acx         bcx
0   -0.373421  -0.1005462 -0.8280985 -0.1593167    1.335307
1    1.324328  -0.6189612  -0.743703  0.9419248    1.282682
2   0.3730312 -0.06697892   1.113707 -0.9691056    1.779643
3  -0.6644958    1.379606 -0.3751724  -1.135034   0.3287292
4   0.4406139  -0.5767996 -0.2267589  -1.384412 -0.03038372
5   -1.242734   -0.838923 -0.6724592   1.405247  -0.3716862
6   -1.682637    -1.69309  -1.291833   1.781704   0.6321988
7  -0.5793783  -0.6809975    1.03502 -0.6498381   -1.124236
8    1.589016    1.272961  -1.968225  0.5515182   0.3058628
9   -2.275342    2.892237   2.076253 -0.1422845 -0.09776171
10          b           b          b          c           c

ix --- lets you read the entire row-- you just say which ever row you want. ix ---让你读完整行 - 你只需说出你想要的那一行。 then you get your columns and assign them to the raw you want. 然后你得到你的列并将它们分配给你想要的原始。

See the example below. 请参阅下面的示例。

virData = DataFrame(df)

virData.columns = virData.ix[1].values

virData.columns

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM