一、dataframe增加行號
dataframe增加行號可以使用reset_index()方法。
import pandas as pd
df = pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})
df = df.reset_index(drop=True)
print(df)
運行結果:
A B
0 1 4
1 2 5
2 3 6
二、dataframe增加na列
dataframe增加na列可以使用pandas.Series()方法。
import pandas as pd
df = pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})
df['C'] = pd.Series([None]*len(df))
print(df)
運行結果:
A B C
0 1 4 None
1 2 5 None
2 3 6 None
三、dataframe添加一行數據
dataframe添加一行數據可以使用append()方法。
import pandas as pd
df = pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})
df = df.append({'A':4,'B':7}, ignore_index=True)
print(df)
運行結果:
A B
0 1 4
1 2 5
2 3 6
3 4 7
四、dataframe增加多行
dataframe增加多行可以使用pd.concat()方法。
import pandas as pd
df1 = pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})
df2 = pd.DataFrame({'A':[7,8,9],'B':[10,11,12]})
df = pd.concat([df1, df2], ignore_index=True)
print(df)
運行結果:
A B
0 1 4
1 2 5
2 3 6
3 7 10
4 8 11
5 9 12
五、dataframe行數
dataframe行數可以使用shape屬性獲取。
import pandas as pd
df = pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})
row_num = df.shape[0]
print(row_num)
運行結果:
3
六、dataframe添加一行
dataframe添加一行可以直接賦值給一個新的Series。
import pandas as pd
df = pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})
new_row = pd.Series({'A':4, 'B':7})
df = df.append(new_row, ignore_index=True)
print(df)
運行結果:
A B
0 1 4
1 2 5
2 3 6
3 4 7
七、dataframe刪除一行
dataframe刪除一行可以使用drop()方法。
import pandas as pd
df = pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})
df = df.drop(1, axis=0)
print(df)
運行結果:
A B
0 1 4
2 3 6
八、dataframe行數統計
dataframe行數統計可以使用value_counts()方法。
import pandas as pd
df = pd.DataFrame({'A':[1,2,3,2,1]})
row_count = df['A'].value_counts()
print(row_count)
運行結果:
2 2
1 2
3 1
Name: A, dtype: int64
九、dataframe求行的和
dataframe求行的和可以使用sum()方法。
import pandas as pd
df = pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})
row_sum = df.sum(axis=1)
print(row_sum)
運行結果:
0 5
1 7
2 9
十、dataframe行選取
dataframe行選取可以使用iloc[]和loc[]方法。
import pandas as pd
df = pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})
row1 = df.iloc[0]
row1_2 = df.loc[df['A']==2]
print(row1)
print(row1_2)
運行結果:
A 1
B 4
Name: 0, dtype: int64
A B
1 2 5
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/193564.html