【发布时间】:2022-01-20 17:51:22
【问题描述】:
假设我有一个如图所示的数据框。
我现在有一个类似 [6,7,6] 的列表。如何将这些填充到我想要的 3 个列中,即数据框的 [one,Two,Four]?请注意,我没有给出“三”列。最终数据框应如下所示:
【问题讨论】:
假设我有一个如图所示的数据框。
我现在有一个类似 [6,7,6] 的列表。如何将这些填充到我想要的 3 个列中,即数据框的 [one,Two,Four]?请注意,我没有给出“三”列。最终数据框应如下所示:
【问题讨论】:
您可以附加一个系列:
df = pd.DataFrame([[2, 4, 4, 8]],
columns=['One', 'Two', 'Three', 'Four'])
values = [6, 3, 6]
lst = ['One', 'Two', 'Four']
df = df.append(pd.Series(values, index=lst), ignore_index=True)
或字典:
df = df.append(dict(zip(lst, values)), ignore_index=True)
输出:
One Two Three Four
0 2.0 4.0 4.0 8.0
1 6.0 3.0 NaN 6.0
【讨论】:
你可以这样做:
columnstobefilled = ["One","Two","Four"]
elementsfill = [6,3,6]
for column,element in zip(columnstobefilled,elementsfill):
df[column] = element
【讨论】:
由于您希望列表值位于特定位置,因此您必须指定每个值的位置。包含此内容的一种方法是使用键值对对象,即字典。创建后,您可以使用 append 将其作为一行包含在数据框中:
d = {'one':6,'Two':7,'Four':6}
df.append(d,ignore_index=True)
one Two Three Four
0 2.0 4.0 4.0 8.0
1 6.0 7.0 NaN 6.0
数据集:
df = pd.DataFrame({'one':2,'Two':4,'Three':4,'Four':8},
index=[0])
【讨论】:
import pandas as pd
df = pd.DataFrame({'One':2, 'Two':4, 'Three':4, 'Four':8}, index=[0])
new_row = {'One':6, 'Two':7, 'Three':None, 'Four':6}
df.append(new_row, ignore_index=True)
print(df)
输出:
One Two Three Four
0 2.0 4.0 4.0 8.0
1 6.0 7.0 NaN 6.0
【讨论】: