简体   繁体   English

如何根据第一列的条件在 pandas 中添加新行?

[英]How to add a new row in pandas based on a condition from the first column?

I have the following pandas dataframe:Example input data我有以下 pandas dataframe:示例输入数据

I would like to iterate through the rows in only the first column and if it meets a condition (ie contains the string 'hello') I would like to add an empty row above this with only the first column being populated.我想只遍历第一列中的行,如果它满足一个条件(即包含字符串'hello'),我想在上面添加一个空行,只填充第一列。

Example output示例output

I have tried: df.loc[0] ='My new title'我试过: df.loc[0] ='My new title'

This adds a row but the title is on every column.这会添加一行,但标题位于每一列。

I'm guessing the syntax would be something like: `我猜语法会是这样的:`

for i in df.iloc[0]:
    if i == 'hello':
    df.loc[-1] ='My new title'
print(df)

` This is not working either - could someone point me in the right direction. ` 这也不起作用 - 有人能指出我正确的方向吗? Thanks谢谢

You can add a new row in this way您可以通过这种方式添加新行

import pandas

data = [['tom', 10], ['nick', 15], ['juli', 14]] 
df = pandas.DataFrame(data, columns = ['Name', 'Age']) 

df2 = pandas.DataFrame([['My new title', None]], columns = ['Name', 'Age'])
rownumber = 0
for i in df.iloc[0:,0]:

    if i == "nick":
        df = pandas.concat([df.iloc[:rownumber], df2, df.iloc[rownumber:]]).reset_index(drop=True)
        rownumber += 1

    rownumber += 1

this will add a new row before every "nick"这将在每个“昵称”之前添加一个新行

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

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