![](/img/trans.png)
[英]How to convert/decode a pandas.Series of mixed bytes/strings into string or utf-8
[英]Pandas: Drop all string components in a mixed typed series with integers and strings
這讓我發瘋。 當我搜索有關在數據框中刪除元素的提示時,沒有關於混合類型系列的內容。
說這是一個數據框:
import pandas as pd
df = pd.DataFrame(data={'col1': [1,2,3,4,'apple','apple'], 'col2': [3,4,5,6,7,8]})
a = df['col1']
那么'a'是一個有6個組件的混合類型系列。 如何從 a 中刪除所有“蘋果”? 我需要系列 = 1,2,3,4。
方法:過濾具有數值的行以保留(而不是將非數值轉換為NaN
然后刪除NaN
) 。 不同之處在於我們不會有NaN
中間結果,這將強制數值從整數變為浮點數。
a = pd.to_numeric(a[a.astype(str).str.isnumeric()])
結果:
生成的 dtype 仍為整數類型int64
print(a)
0 1
1 2
2 3
3 4
Name: col1, dtype: int64
NaN
生成中間結果,如下所示:a = pd.to_numeric(a, errors='coerce').dropna()
生成的 dtype 被迫更改為float
類型(而不是保留為整數)
0 1.0
1 2.0
2 3.0
3 4.0
Name: col1, dtype: float64
您可以按標簽刪除,其中標簽包含索引值列表。
df = pd.DataFrame(data={'col1': [1,2,3,4,'apple','apple'], 'col2': [3,4,5,6,7,8]})
df.reset_index(inplace=True)
print(df)
grouped=df.col1.str.isnumeric().eq(0)
labels=set([x for x in (grouped[grouped.values==True].index)])
if len(labels)>0:
df = df.drop(labels=labels, axis=0)
輸出:
index col1 col2
0 0 1 3
1 1 2 4
2 2 3 5
3 3 4 6
4 4 apple 7
5 5 apple 8
您可以使用 apply 方法並使用 lambda 標記字符串,並將它們替換為 NaN 之類的值以過濾掉它們。
import numpy as np
a = df['col1'].apply(lambda x: np.nan if isinstance(x, str) else x).dropna()
這段代碼的作用是:
這也避免了錯誤地強制可能包含有效整數/浮點數的字符串元素,例如,如果列中有像“12”這樣的元素,假設這不是您想要的行為。
此外,如果您希望最終輸出為 int 類型,您可以像這樣映射它:
a = df['col1'].apply(lambda x: np.nan if isinstance(x, str) else x).dropna().map(int)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.