python - 在数据框的列之间创建成对关系

标签 python python-3.x pandas dataframe

<分区>

我有一个数据框如下:

Neighborhood, City, State, Country       

Westside, Boston, MA,USA
South District, New York,NY,USA
Business Town,,OR,USA
Shopping District,,Wellington,New Zealand
Big Mountain,,,Australia

现在我想遍历成对的非空列 C0,C1 C1,C2 C2,C3 并创建如下所示的数据框。但是 如果 C1 为空或 null,则将 C0 与 C2 配对,依此类推

Root               Child
 OR                  Business Town
 USA                 OR
 New Zealand         Wellington
 Wellington.         Shopping District 
 Boston              Westside
 MA                  Boston
 USA                 MA
 New York            South District
 NY                  New York
 USA                 NY
 Australia          Big Mountain

最佳答案

这是在 stack 之后使用 shift 的一种方法

s=df.stack().iloc[::-1]
yourdf=pd.DataFrame({'Root':s.groupby(level=0).shift().values,'Child':s.values}).dropna()
yourdf
Out[62]: 
           Root              Child
1     Australia       Big Mountain
3   New Zealand         Wellington
4    Wellington  Shopping District
6           USA                 OR
7            OR      Business Town
9           USA                 NY
10           NY           New York
11     New York     South District
13          USA                 MA
14           MA             Boston
15       Boston           Westside

关于python - 在数据框的列之间创建成对关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57154329/

相关文章:

python - Pandas 将 dtype 对象转换为字符串

Python numpy 屏蔽数组初始化

python - 将站点包复制到我自己的元素中以获得 'local copy'

python - 如何使用字符串过滤日期?

python - 初学者 python 循环

python - gspread update_cell 非常慢

python - Python 中的多处理 : execute two functions at the exact same time

c++ - 使用 boost::python 从 C++ 创建 python collections.namedtuple

python - 如何根据列的过滤条件删除行

python - 使用 pandas 根据 groupby 将行中的多个变量转置为列