官术网_书友最值得收藏!

Concatenating and appending DataFrames

The Pandas DataFrame allows operations that are similar to the inner and outer joins of database tables. We can append and concatenate rows as well. To practice appending and concatenating of rows, we will reuse the DataFrame from the previous section. Let's select the first three rows:

print("df :3\n", df[:3]) 

Check that these are indeed the first three rows:

df :3
       Food  Number     Price Weather
0      soup       8  3.745401    cold
1      soup       5  9.507143     hot
2  icecream       4  7.319939    cold

The concat() function concatenates DataFrames. For example, we can concatenate a DataFrame that consists of three rows to the rest of the rows, in order to recreate the original DataFrame:

print("Concat Back together\n", pd.concat([df[:3], df[3:]])) 

The concatenation output appears as follows:

Concat Back together
        Food  Number     Price Weather
0       soup       8  3.745401    cold
1       soup       5  9.507143     hot
2   icecream       4  7.319939    cold
3  chocolate       8  5.986585     hot
4   icecream       8  1.560186    cold
5   icecream       3  1.559945     hot
6       soup       6  0.580836    cold

[7 rows x 4 columns]

To append rows, use the append() function:

print("Appending rows\n", df[:3].append(df[5:])) 

The result is a DataFrame with the first three rows of the original DataFrame and the last two rows appended to it:

Appending rows
       Food  Number     Price Weather
0      soup       8  3.745401    cold
1      soup       5  9.507143     hot
2  icecream       4  7.319939    cold
5  icecream       3  1.559945     hot
6      soup       6  0.580836    cold

[5 rows x 4 columns]
主站蜘蛛池模板: 长葛市| 库伦旗| 财经| 西城区| 屯门区| 西和县| 清水县| 塔城市| 海林市| 田东县| 新龙县| 蓬莱市| 日照市| 体育| 临洮县| 冀州市| 弥勒县| 类乌齐县| 林周县| 社旗县| 阳山县| 油尖旺区| 兰西县| 万源市| 宁安市| 长丰县| 松阳县| 金沙县| 平顺县| 彰武县| 苗栗市| 城固县| 海晏县| 社会| 武宣县| 海宁市| 博湖县| 新沂市| 望谟县| 监利县| 丰镇市|