将字典和系列列表附加到Python现有的 Pandas DataFrame
在本文中,我们将讨论如何将字典列表或 Pandas 系列中的值附加到现有的 Pandas 数据框。为此,pandas 的 append()函数,该模块就足够了。
Syntax: DataFrame.append(other, ignore_index=False, verify_integrity=False, sort=None)
Parameters :
other : DataFrame or Series/dict-like object, or list of these
ignore_index : If True, do not use the index labels.
verify_integrity : If True, raise ValueError on creating index with duplicates.
sort : Sort columns if the columns of self and other are not aligned. The default sorting is deprecated and will change to not-sorting in a future version of pandas. Explicitly pass sort=True to silence the warning and sort. Explicitly pass sort=False to silence the warning and not sort.
Returns: appended : DataFrame
方法
- 导入模块
- 创建数据框或系列
- 创建包含字典的列表
- 将此列表附加到现有数据框或系列
示例 1:
Python
# import pandas
import pandas as pd
# create dataframe
df = pd.DataFrame({
'Employs Name': ['Rishabh', 'Rahul', 'Suraj', 'Mukul', 'Vinit'],
'Location': ['Saharanpur', 'Meerut', 'Saharanpur', 'Meerut', 'Saharanpur'],
'Pay': [21000, 22000, 23000, 24000, 22000]})
# print dataframe
print("\n *** Original DataFrames ** \n")
print(df)
# create dictionaries
dicts = [{'Employs Name': 'Anuj', 'Location': 'Meerut', 'Roll No': 30000},
{'Employs Name': 'Arun', 'Location': 'Saharanpur', 'Roll No': 32000}]
# print dictionaries
print("\n ** Dictionary ** ")
print(dicts)
# combined data
df = df.append(dicts, ignore_index=True, sort=False)
# print combined dataframe
print("\n\n ** Combined Data **\n")
print(df)
Python
# import pandas
import pandas as pd
# create dataframe
df = pd.DataFrame({
'Name': ['Mukul', 'Rohit', 'Suraj', 'Rohan', 'Rajan'],
'Course': ['BBA', 'BCA', 'MBA', 'BCA', 'BBA'],
'Roll No': [21, 22, 23, 24, 25]})
# print dataframe
print("\n *** Original DataFrames ** ")
display(df)
# create series
s6 = pd.Series(['Vedansh', 'MBA', 29], index=['Name', 'Course', 'Roll No'])
# print series
print("\n *** series ** ")
print(s6)
# create dictionaries
dicts = [{'Name': 'Aakash', 'Course': 'BCA', 'Roll No': 30}]
# print dictionaries
print("\n ** Dictionary ** ")
print(dicts)
# combined data
df = df.append(dicts, ignore_index=True, sort=False)
print("\n ** Combined Data **")
display(df)
输出:
示例 2:
Python
# import pandas
import pandas as pd
# create dataframe
df = pd.DataFrame({
'Name': ['Mukul', 'Rohit', 'Suraj', 'Rohan', 'Rajan'],
'Course': ['BBA', 'BCA', 'MBA', 'BCA', 'BBA'],
'Roll No': [21, 22, 23, 24, 25]})
# print dataframe
print("\n *** Original DataFrames ** ")
display(df)
# create series
s6 = pd.Series(['Vedansh', 'MBA', 29], index=['Name', 'Course', 'Roll No'])
# print series
print("\n *** series ** ")
print(s6)
# create dictionaries
dicts = [{'Name': 'Aakash', 'Course': 'BCA', 'Roll No': 30}]
# print dictionaries
print("\n ** Dictionary ** ")
print(dicts)
# combined data
df = df.append(dicts, ignore_index=True, sort=False)
print("\n ** Combined Data **")
display(df)
输出: