データフレームは単一の行を追加します
メソッドの割り当て
データフレーム割り当てメソッドは、古いデータフレームオブジェクトに影響を与えることなく、新しいオブジェクト(コピー)を返します。
import pandas as pd
df = pd.DataFrame({
'col_1': [0, 1, 2, 3],
'col_2': [4, 5, 6, 7]
})
sLength = len(df['col_1'])
df2 = df.assign(col_3=pd.Series([8, 9, 10, 11]).values)
print(df)
print(df2)
結果表示:
col_1 col_2
0 0 4
1 1 5
2 2 6
3 3 7
col_1 col_2 col_3
0 0 4 8
1 1 5 9
2 2 6 10
3 3 7 11
簡単な方法と挿入方法
単純なメソッドdf ['col_3'] = pd.Series([8、9、10、11])
挿入メソッドdf.insert(loc = len(df.columns)、column =“ col_4”、value = [8、 9、10、11])
このメソッドは、古いデータフレームに新しい列を追加します
import pandas as pd
df = pd.DataFrame({
'col_1': [0, 1, 2, 3],
'col_2': [4, 5, 6, 7]
})
df['col_3'] = pd.Series([8, 9, 10, 11])
print(df)
df.insert(loc=len(df.columns), column="col_4", value=[8, 9, 10, 11])
print(df)
データフレームはさらに列を追加します
リストの開梱
import pandas as pd
import numpy as np
df = pd.DataFrame({
'col_1': [0, 1, 2, 3],
'col_2': [4, 5, 6, 7]
})
df['column_new_1'], df['column_new_2'], df['column_new_3'] = [np.nan, 'dogs', 3]
print(df)
結果表示:
col_1 col_2 column_new_1 column_new_2 column_new_3
0 0 4 NaN dogs 3
1 1 5 NaN dogs 3
2 2 6 NaN dogs 3
3 3 7 NaN dogs 3
DataFrameも1行で一致できます
df[['column_new_1', 'column_new_2', 'column_new_3']] = pd.DataFrame([[np.nan, 'dogs', 3]], index=df.index)
concatメソッド
df = pd.concat(
[
df,
pd.DataFrame(
[[np.nan, 'dogs', 3]],
index=df.index,
columns=['column_new_1', 'column_new_2', 'column_new_3']
)
], axis=1
)
結合メソッド
df = df.join(pd.DataFrame(
[[np.nan, 'dogs', 3]],
index=df.index,
columns=['column_new_1', 'column_new_2', 'column_new_3']
))
参加+辞書
df = df.join(pd.DataFrame(
{
'column_new_1': np.nan,
'column_new_2': 'dogs',
'column_new_3': 3
}, index=df.index
))
メソッドの割り当て
df = df.assign(column_new_1=np.nan, column_new_2='dogs', column_new_3=3)
土壌法
df['column_new_1'] = np.nan
df['column_new_2'] = 'dogs'
df['column_new_3'] = 3