【问题标题】:How to select certain rows from a dataframe in pandas如何从熊猫的数据框中选择某些行
【发布时间】:2018-09-19 06:38:37
【问题描述】:

1- 如何在一列中选择 5 个不同的值?

例子:

**Car**

Fiat
Fiat
Hyundai
Mitsubish
Kia
Kia
Hyundai
renault
porsche

如何选择具有(菲亚特、现代、起亚)的行?

我试过这个:

df.loc[df['cars'].isin("Fiat", "hyundai" , "Kia")]

但没有成功

第二个问题:

在 R 中,我们有管道运算符以减少新副本的数量*。 python中最好的解决方案是什么?

*Update - 创建多步骤操作数据的好方法吗?

在这个例子中:

df1 = df1.dropna()
df1 = df1[(df1['Meses'] != 'Total') & (df1['Orcado x Realizado'] == 'Realizado') & (df1['Area Negocio'] == 'Total das Áreas de Negócios')]
df1['Meses'] = df1['Meses'].replace({'M1': '01', 'M2': '02', 'M3': '03', 'M4': '04', 'M5': '05', 'M4': '04', 'M5': '05', 'M6': '06', 'M7': '07', 'M8': '08', 'M9': '09', 'M10': '10', 'M11': '11', 'M12': '12'})
df1['Date'] = pd.to_datetime(df1.Ano.astype(str) + '-' + df1.Meses.astype(str))
df1['Values'] = (df1['Values'] / 1000000)
df1 = df1[['Date', 'Contas Resultado', 'Values']]

有没有办法让这段代码更短,而不必创建新变量?

【问题讨论】:

  • 你能包括原始数据框的样子吗?
  • 对于您的第一个问题,只需将您的汽车品牌放入您的.isin():df.loc[df['cars'].isin(["Fiat", "hyundai" , "Kia"])]的列表中

标签: python pandas numpy data-manipulation


【解决方案1】:

第一个问题:

使用此代码:

df.loc[df['cars'].isin("Fiat", "hyundai" , "Kia")]

你需要使用一个列表:

df.loc[df['cars'].isin(["Fiat", "hyundai" , "Kia"])]

第二个问题:

我不确定您所说的创建新变量是什么意思。看起来你只有一个 (df1)

编辑

这段代码:

df1 = df1.dropna()
df1 = df1[(df1['Meses'] != 'Total') & (df1['Orcado x Realizado'] == 'Realizado') & (df1['Area Negocio'] == 'Total das Áreas de Negócios')]
df1['Meses'] = df1['Meses'].replace({'M1': '01', 'M2': '02', 'M3': '03', 'M4': '04', 'M5': '05', 'M4': '04', 'M5': '05', 'M6': '06', 'M7': '07', 'M8': '08', 'M9': '09', 'M10': '10', 'M11': '11', 'M12': '12'})
df1['Date'] = pd.to_datetime(df1.Ano.astype(str) + '-' + df1.Meses.astype(str))
df1['Values'] = (df1['Values'] / 1000000)
df1 = df1[['Date', 'Contas Resultado', 'Values']]

可以简化为:

df1.dropna(inplace = True) # shortened
df1 = df1[(df1['Meses'] != 'Total') & (df1['Orcado x Realizado'] == 'Realizado') & (df1['Area Negocio'] == 'Total das Áreas de Negócios')]
df1['Meses'].replace({'M1': '01', 'M2': '02', 'M3': '03', 'M4': '04', 'M5': '05', 'M4': '04', 'M5': '05', 'M6': '06', 'M7': '07', 'M8': '08', 'M9': '09', 'M10': '10', 'M11': '11', 'M12': '12'}, inplace = True) # shortened
df1['Date'] = pd.to_datetime(df1.Ano.astype(str) + '-' + df1.Meses.astype(str))
df1['Values'] = (df1['Values'] / 1000000)
df1 = df1[['Date', 'Contas Resultado', 'Values']]

除了在可用时使用inplace= 参数之外,真的不能做更多的“缩短”。

【讨论】:

  • 当我多次写“df1= ...”时,它是执行多个操作步骤的好方法吗?或者它比必要的过程多?
  • 谢谢。只是为了确认:在这种情况下,df1 变量的每个新副本都是必要的?
  • @Cesar 是正确的。您也许可以使用pandas.pydata.org/pandas-docs/stable/generated/…,但如果没有看到您的一些数据,我无法确认。
猜你喜欢
  • 2016-11-06
  • 1970-01-01
  • 2016-02-17
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多