[英]How to remove every n-th element from dataframe column in python
我正在使用 python 并有一个从 Z628CB5675FF524F3E719BFEAAZE8 导入的 pandas dataframe。 我想从特定列中的每个条目中删除每个第 n 个值。
例如:
要转换的 dataframe 列称为:
“线串”
Linestring(151.420 -33.540, 155.464722 -39.069046, 153.30925678 -33.08364825, 152.0998 -31.8090, 150.539067 -30.57578)
每个条目都有不同的长度
我想在每个逗号给出后删除每两个元素: Linestring(151.420 -33.540, 153.30925678 -33.08364825, 150.539067 -30.57578)
附加/链接是我所追求的视觉指南。
示例问题和结果
非常感谢: :)
尝试这个。 我希望它会有所帮助。
df['Linestring'] = df.Linestring.apply(lambda x: ','.join(x.split(',')[::2]) if ','.join(x.split(',')[::2])[-1] == ')' else ','.join(x.split(',')[::2]) + ')')
我写了一个 function 用 None 替换每个第 n 个值,然后您可以删除这些值,留下一个不包含这些删除单元格的新数据框。 我希望这有帮助。
import pandas as pd
df = pd.DataFrame({'Numbers': [10,15,33,22,17,77,9]}) #a dataframe with column and some values
print(df) #prints the original dataframe
def rmNth(dFrame, col, n): #dataframe, column, delete every 'nth'
rows = len(dFrame.axes[0]) #stores the number of rows
x = n - 1 #used in the while loop
while (x <= rows): #replace every nth cell with a null value
dFrame.at[x ,col] = None
x = x + n #increment x by n
print(dFrame) #prints the dataframe showing all cells that will be removed are replaced with 'nan'
newDF = dFrame.dropna() #remove null cells
newDF.reset_index(drop=True, inplace=True) #reset the index
return (newDF)
print(rmNth(df, "Numbers", 3)) #print the data frame with every 3rd value removed from the Numbers column
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.