简体   繁体   English

Python Dataframe 根据列名添加新行

[英]Python Dataframe add new row based on column name

How do I add a new row to my dataframe, with values that are based on the column names?如何使用基于列名的值向我的 dataframe 添加新行?

For example例如

Dog = 'happy'
Cat = 'sad'
df = pd.DataFrame(columns=['Dog', 'Cat'])

I want to add a new line to the dataframe where is pulls in the variable of the column heading我想在 dataframe 中添加一个新行,其中拉入列标题的变量

      Dog   Cat
0   happy   sad

You can try append :您可以尝试append

df.append({'Dog':Dog,'Cat':Cat}, ignore_index=True)

Output: Output:

     Dog  Cat
0  happy  sad

You can use append in a different way(other than mentioned above one)您可以以不同的方式使用 append(上述方式除外)

df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
df

output:
   A  B
0  1  2
1  3  4

df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'))
df.append(df2)

output:
   A  B
0  1  2
1  3  4
0  5  6
1  7  

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

相关问题 如何基于熊猫数据框中的行条件添加新列? - How to add new column based on row condition in pandas dataframe? 在dataframe列的每一行中查找单词并添加一个新列 - Python - Find for a word in a each row of dataframe column and add a new column - Python Pandas DataFrame:添加具有基于前一行计算值的新列 - Pandas DataFrame: Add new column with calculated values based on previous row 根据 dataframe 中的其他行值添加新列 - add a new column based on other row values in dataframe 根据行中的第一个值向数据框添加新列 - Add a new column to a dataframe based on first value in row Python:根据 dataframe 中的现有列添加带有日期的新列 - Python : Add a new column with date based on existing column in dataframe Python:根据DataFrame中的列名创建新行 - Python: create new row based on column names in DataFrame 将 dataframe 的名称传递到每个行中,以获取数据框列表中的新列 Python - Pass the name of the dataframe into each for row for a new column in a list of dataframes Python Python数据框:根据数据框另一列的字符串行中是否包含列名,将行填充为1或0 - Python Dataframe: Fill in Row as 1 or 0 Based on If Column Name is Contained in String Row of Another Column in Dataframe 将新的列元素显式添加到Pandas DataFrame(Python 2)中的现有行 - Add new column elements to explicitly to existing row in Pandas DataFrame (Python 2)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM