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

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]
主站蜘蛛池模板: 梧州市| 亳州市| 连城县| 廉江市| 亚东县| 临洮县| 溆浦县| 额敏县| 钦州市| 罗源县| 汉阴县| 贺州市| 新兴县| 那曲县| 江都市| 扶风县| 安化县| 和平县| 新乐市| 乡城县| 咸阳市| 沧源| 平潭县| 平谷区| 平泉县| 炎陵县| 南丹县| 龙岩市| 四会市| 应城市| 永寿县| 岳池县| 靖州| 大安市| 延寿县| 曲沃县| 名山县| 泰安市| 日喀则市| 乐东| 轮台县|