Pandas 数据帧explode()
方法
原文:https://www.studytonight.com/pandas/pandas-dataframe-explode-method
在本教程中,我们将学习 PandasDataFrame.explode()
T3】法。它将列表中的每个元素转换为一行,复制索引值。它将数据帧分解列表返回给子集列的行;将为这些行复制索引。
下图显示了DataFrame.explode()
方法的语法。
句法
DataFrame.explode(column, ignore_index=False)
因素
列:字符串或元组。柱子要爆炸了。
ignore_index: bool,默认 False。如果为真,结果索引将被标记为 0,1,…,n - 1。
示例 1:使用DataFrame.explode()
方法分解数据帧
如果数据帧列中的某些元素由列表组成,我们可以使用DataFrame.explode()
方法将其扩展到多个列。下面的例子显示了同样的情况。
#importing pandas as pd
import pandas as pd
df = pd.DataFrame({'A': [[1,3],[3]], 'B': 1})
print("------The DataFrame is--------")
print(df)
print("After expanding the DataFrame")
print(df.explode('A'))
一旦我们运行该程序,我们将获得以下输出。
-展开数据帧 A B 0 1 0 3 1 1 3 1 后,数据帧为- A B 0 1 0 3 1 1 3 1
示例 2:使用DataFrame.explode()
方法分解数据帧
这个例子和前面的例子类似,只是我们使用了ignore_index=True
参数,得到的索引会被标记为 0,1,…,n - 1。
#importing pandas as pd
import pandas as pd
df = pd.DataFrame({'A': [[1,3],[4]], 'B': 1})
print("------The DataFrame is--------")
print(df)
print("After expanding the DataFrame")
print(df.explode('A',ignore_index=True))
一旦我们运行该程序,我们将获得以下输出。
-展开数据帧 A B 0 1 1 3 1 2 4 1 后,数据帧为- A B 0 [1,3] 1 1 [4] 1
示例 3:使用DataFrame.explode()
方法分解数据帧
这个例子类似于前面的例子。空列表将被扩展成一个numpy.nan
值。
#importing pandas as pd
import pandas as pd
df = pd.DataFrame({'A': [[1, 2], []], 'B': 1})
print("------The DataFrame is--------")
print(df)
print("After expanding the DataFrame")
print(df.explode('A',ignore_index=True))
一旦我们运行该程序,我们将获得以下输出。
-展开数据帧 A B 0 1 1 2 1 2 NaN 1 后,数据帧为- A B 0 [1,2]1 1【】1
结论
在本教程中,我们学习了 PandasDataFrame.explode()
方法。我们学习了语法、参数,并通过在由作为元素的列表组成的数据帧上应用这种方法解决了一些例子。