[英]Split one column to two columns depending one the content in pandas dataframe
我有一個這樣的熊貓DataFrame:
df = pd.DataFrame(['A',1,2,3,'B',4,5,'C',6,7,8,9])
0
0 A
1 1
2 2
3 3
4 B
5 4
6 5
7 C
8 6
9 7
10 8
11 9
它是字符串和數字的混合。 我想將此DF分成這樣的兩個列:
name value
0 A 1
1 A 2
2 A 3
3 B 4
4 B 5
5 C 6
6 C 7
7 C 8
8 C 9
什么是有效的方法?
您可以使用:
df = pd.DataFrame({0 :['A',1,2,3,'B',4,5,'C',6,7,8,9]})
#check strings
mask = df[0].astype(str).str.isalpha()
#check if mixed values - numeric with strings
#mask = df[0].apply(lambda x: isinstance(x, str))
#create column to first position, create NaNs filled by forward filling
df.insert(0, 'name', df[0].where(mask).ffill())
#remove rows with same values - with names, rename column
df = df[df['name'] != df[0]].rename(columns={0:'value'}).reset_index(drop=True)
print (df)
name value
0 A 1
1 A 2
2 A 3
3 B 4
4 B 5
5 C 6
6 C 7
7 C 8
8 C 9
要么:
out = []
acc = None
for x in df[0]:
#check if strings
if isinstance(x, str):
#assign to variable for tuples
acc = x
else:
#append tuple to out
out.append((acc, x))
print (out)
df = pd.DataFrame(out, columns=['name','value'])
print (df)
name value
0 A 1
1 A 2
2 A 3
3 B 4
4 B 5
5 C 6
6 C 7
7 C 8
8 C 9
這將使您獲得所需的數據結構:
input = ['A',1,2,3,'B',4,5,'C',6,7,8,9]
letter = None
output = []
for i in input:
if type(i) is type(''):
letter = i
elif type(i) is type(0) and letter is not None:
output.append((letter, i))
print(output)
現在,輸出具有一個元組序列,可以根據需要進行配對。 我不使用熊貓 ,但我希望這對您有所幫助。
IIUC
df['New']=df[df.your.str.isalpha().fillna(False)]
df.ffill().loc[df.your!=df.New,:]
Out[217]:
your New
1 1 A
2 2 A
3 3 A
5 4 B
6 5 B
8 6 C
9 7 C
10 8 C
11 9 C
數據輸入
df = pd.DataFrame({'your':['A',1,2,3,'B',4,5,'C',6,7,8,9]})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.