![](/img/trans.png)
[英]Spliting strings values of a column out of index and fill with NaN in a Pandas DataFrame
[英]How do I manipulate pandas DataFrame with a column that has rows with strings that needs spliting
我有一個類似於表A的熊貓數據框,我想獲取表B。用熊貓做這件事的最簡單方法是什么?
謝謝
表A(ColofInt具有不同長度的字符串要解析):
ColA ColB ColofInt ColD
A B StrA;StrB;StrC; 1
A B StrD;StrB;StrC;StrD; 3
A B StrC;StrB; 2
A B StrB; 5
表B:
ColA ColB ColofInt1 ColofInt2 ColofInt2 ColofInt3 ColD
A B StrA StrB StrC 1
A B StrD StrB StrC StrD 3
A B StrC StrB 2
A B StrB 5
假設文件“ tableA.csv”包含以下內容:
ColA,ColB,ColofInt,ColD
A,B,StrA;StrB;StrC;,1
A,B,StrD;StrB;StrC;StrD;,3
A,B,StrC;StrB;,2
A,B,StrB;,5
然后:
import pandas as pd
tableA= pd.read_csv('tableA.csv')
這將使用您的新列生成一個數據框
data_aux = pd.DataFrame(list(tableA.ColofInt.str.split(';').apply(lambda x: x[:-1])))
cols = []
for e in data_aux .columns:
cols.append('ColofInt' + str(e+1))
data_aux .columns = cols
繼承人“ data_aux”:
ColofInt1 ColofInt2 ColofInt3 ColofInt4
0 StrA StrB StrC None
1 StrD StrB StrC StrD
2 StrC StrB None None
3 StrB None None None
並且這將連接數據框,並刪除原始列。
tableB = pd.concat([tableA,data_aux],axis=1).drop('ColofInt',axis=1)
這是生成的“ tableB”:
ColA ColB ColD ColofInt1 ColofInt2 ColofInt3 ColofInt4
0 A B 1 StrA StrB StrC None
1 A B 3 StrD StrB StrC StrD
2 A B 2 StrC StrB None None
3 A B 5 StrB None None None
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.